1. 程式人生 > >java基礎的核心技術:多執行緒(一)

java基礎的核心技術:多執行緒(一)

1、程式、程序、執行緒的概念

2、java中多執行緒的建立和使用(重點)

2.1、繼承Thread類與實現Runnable介面

2.2、Thread類的主要方法

2.3、執行緒的排程與設定優先順序

3、執行緒的生命週期

4、執行緒的同步(重點)

5、執行緒的通訊 

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------

一、基本概念: 程式--程序--執行緒

1) 程式(Program): 是為完成特定任務、用某種語言編寫的一組指令的集合。即指一段靜態的程式碼,靜態物件。

2) 程序(process):是程式的一次執行過程,或是正在執行的一個程式,動態過程:有它自身的產生、存在和消亡的過程。

-->如:執行中的QQ,執行中的MP3播放器

-->程式是靜態的,程序是動態的

3) 執行緒(Thread):程序可進一步細化為執行緒,是一個程式內部的一條執行路徑。

-->若一個程式可同一時間執行多個執行緒,就是支援多執行緒的

4) 每個Java程式都有一個隱含的主執行緒:main()方法

問題:何時需要多執行緒?

程式需要同時執行兩個或多個任務

程式需要實現一些需要等待的任務時,如使用者輸入、檔案讀寫操作、網路操作、搜尋等 。

需要一些後臺執行的程式時。


--------------------------------------------------------------------------------------------------------------------------------------------------------------------------

二、建立多執行緒

什麼是單執行緒?

package com.attest.java1;
//單執行緒 主執行緒
public class TestMain {
	public static void main(String[] args) {
		method2("atTestThread");
	}
	public static void method1(String str){
		System.out.println("method1.....");
		System.out.println(str);
	}
	public static void method2(String str){
		System.out.println("method2.....");
		method1(str);
	}
}
運程的結果:無論你怎麼運程,結果只有一個:




--------------------------------------------------------------------------------------------------------------------------------------------------------------------------

多執行緒的建立和啟動的步驟:

1、Java語言的JVM允許程式執行多個執行緒,它通過java.lang.Thread類來實現。

2、Thread類的特性

2.1、每個純種都是通過某個特定Thread物件的run()方法來完成操作的。經常把run()方法的主體稱為執行緒體。

2.2、通過該Thread物件的start()方法來呼叫這個執行緒

看一下Java-jdk的api是怎麼說的(這是從java api 1.7.0摘抄而來的)

java.lang
類 Thread
java.lang.Object 
java.lang.Thread 

所有已實現的介面: 
Runnable 
直接已知子類: 
ForkJoinWorkerThread 

--------------------------------------------------------------------------------


public class Thread
extends Object
implements RunnableA thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently. 
Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority. Each thread may or may not also be marked as a daemon. When code running in some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the creating thread, and is a daemon thread if and only if the creating thread is a daemon. 

When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs: 

The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place. 
All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method. 
There are two ways to create a new thread of execution. One is to declare a class to be a subclass of Thread. This subclass should override the run method of class Thread. An instance of the subclass can then be allocated and started. For example, a thread that computes primes larger than a stated value could be written as follows: 



--------------------------------------------------------------------------------

     class PrimeThread extends Thread {
         long minPrime;
         PrimeThread(long minPrime) {
             this.minPrime = minPrime;
         }

         public void run() {
             // compute primes larger than minPrime
              . . .
         }
     }
 
--------------------------------------------------------------------------------

The following code would then create a thread and start it running: 


     PrimeThread p = new PrimeThread(143);
     p.start();
 The other way to create a thread is to declare a class that implements the Runnable interface. That class then implements the run method. An instance of the class can then be allocated, passed as an argument when creating Thread, and started. The same example in this other style looks like the following: 



--------------------------------------------------------------------------------

     class PrimeRun implements Runnable {
         long minPrime;
         PrimeRun(long minPrime) {
             this.minPrime = minPrime;
         }

         public void run() {
             // compute primes larger than minPrime
              . . .
         }
     }
 
--------------------------------------------------------------------------------

The following code would then create a thread and start it running: 


     PrimeRun p = new PrimeRun(143);
     new Thread(p).start();
 Every thread has a name for identification purposes. More than one thread may have the same name. If a name is not specified when a thread is created, a new name is generated for it. 

Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.


例子:建立執行緒

package com.attest.java1;

/*
 * 建立一個子執行緒,完成1-100之間自然數的輸出。同樣的,主執行緒執行同樣的操作
 * 建立多執行緒的第一種方式,繼承java.lang.Thread類
 */
//1、建立一個繼承於Thread的子類
class SubThread extends Thread {
	// 重寫Thread類的run( )方法,方法內實現此子執行緒想要完成的功能
	@Override
	public void run() {
		for (int i = 0; i <= 100; i++) {
			System.out.println(Thread.currentThread().getName() + " : " + i);
		}
	}

}

public class TestThread {
	public static void main(String[] args) {
		// 3、建立一個子類的物件
		SubThread subT = new SubThread();
		// 4、呼叫執行緒的start( ),啟動此執行緒,呼叫相應的run( )方法
		subT.start();
		for (int i = 0; i <= 100; i++) {
			System.out.println(Thread.currentThread().getName() + " : " + i);
		}
	}

}
結果如下:



-------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------