標籤:
如前所述,通常你希望主線程最後結束。在前面的例子中,這點是通過在main()中調用sleep()來實現的,經過足夠長時間的延遲以確保所有子線程都先於主線程結束。然而,這不是一個令人滿意的解決方案,它也帶來一個大問題:一個線程如何知道另一線程已經結束?幸運的是,Thread類提供了回答此問題的方法。
有兩種方法可以判定一個線程是否結束。第一,可以線上程中調用isAlive()。這種方法由Thread定義,它的通常形式如下:
final boolean isAlive( )
如果所調用線程仍在運行,isAlive()方法返回true,如果不是則返回false。但isAlive()很少用到,等待線程結束的更常用的方法是調用join(),描述如下:
final void join( ) throws InterruptedException
該方法等待所調用線程結束。該名字來自於要求線程等待直到指定線程參與的概念。join()的附加形式允許給等待指定線程結束定義一個最大時間。下面是前面例子的改進版本。運用join()以確保主線程最後結束。同樣,它也示範了isAlive()方法。
1 // Using join() to wait for threads to finish. 2 class NewThread implements Runnable { 3 String name; // name of thread 4 Thread t; 5 NewThread(String threadname) { 6 name = threadname; 7 t = new Thread(this, name); 8 System.out.println("New thread: " + t); 9 t.start(); // Start the thread10 }11 // This is the entry point for thread.12 public void run() {13 try {14 for(int i = 5; i > 0; i--) {15 System.out.println(name + ": " + i);16 Thread.sleep(1000);17 }18 } catch (InterruptedException e) {19 System.out.println(name + " interrupted.");20 }21 System.out.println(name + " exiting.");22 }23 }24 25 class DemoJoin {26 public static void main(String args[]) {27 NewThread ob1 = new NewThread("One");28 NewThread ob2 = new NewThread("Two");29 NewThread ob3 = new NewThread("Three");30 System.out.println("Thread One is alive: "+ ob1.t.isAlive());31 System.out.println("Thread Two is alive: "+ ob2.t.isAlive());32 System.out.println("Thread Three is alive: "+ ob3.t.isAlive());33 // wait for threads to finish34 try {35 System.out.println("Waiting for threads to finish.");36 ob1.t.join();37 ob2.t.join();38 ob3.t.join();39 } catch (InterruptedException e) {40 System.out.println("Main thread Interrupted");41 }42 System.out.println("Thread One is alive: "+ ob1.t.isAlive());43 System.out.println("Thread Two is alive: "+ ob2.t.isAlive());44 System.out.println("Thread Three is alive: "+ ob3.t.isAlive());45 System.out.println("Main thread exiting.");46 }47 }
程式輸出如下所示:
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
Thread One is alive: true
Thread Two is alive: true
Thread Three is alive: true
Waiting for threads to finish.
One: 5
Two: 5
Three: 5
One: 4
Two: 4
Three: 4
One: 3
Two: 3
Three: 3
One: 2
Two: 2
Three: 2
One: 1
Two: 1
Three: 1
Two exiting.
Three exiting.
One exiting.
Thread One is alive: false
Thread Two is alive: false
Thread Three is alive: false
Main thread exiting.
如你所見,調用join()後返回,線程終止執行。
系列文章:
Java知多少(上)
Java知多少(39)interface介面
Java知多少(40)介面和抽象類別的區別
Java知多少(41)泛型詳解
Java知多少(42)泛型萬用字元和型別參數的範圍
Java知多少(43)異常處理基礎
Java知多少(44)異常類型
Java知多少(45)未被捕獲的異常
Java知多少(46)try和catch的使用
Java知多少(47)多重catch語句的使用
Java知多少(48)try語句的嵌套
Java知多少(49)throw:異常的拋出
Java知多少(50)Java throws子句
Java知多少(51)finally
Java知多少(52)內建異常
Java知多少(53)使用Java建立自己的異常子類
Java知多少(54)斷言詳解
Java知多少(55)線程
Java知多少(56)執行緒模式Java知多少(57)主線程Java知多少(58)線程Runnable介面和Thread類詳解Java知多少(59)建立多線程
Java知多少(60)isAlive()和join()的使用