南京達內培訓講師表示,Java線程的join方法可用于暫停當前線程的執行直至目標線程死亡。Thread中一共有三個join的重載方法。
public final void join():該方法將當前線程放入等待隊列中,直至被它調用的線程死亡為止。如果該線程被中斷,則會拋出InterruptedException異常。
public final synchronized void join(long millis):該方法用于讓當前線程進入等待狀態,直至被它調用的線程死亡或是經過millis毫秒。由于線程的執行依賴于操作系統,所以該方法無法保證當前線程等待的時間和指定時間一致。
public final synchronized void join(long millis, int nanos):該方法用于讓線程暫停millis毫秒nanos納秒。
下面的例子演示了join方法的使用。該段代碼的目的是確保main線程最后結束,并且僅當第一個線程死亡才能啟動第三個線程。
ThreadJoinExample.java
package com.journaldev.threads;
public class ThreadJoinExample {
Thread t1 = new Thread(new MyRunnable(), t1);
Thread t2 = new Thread(new MyRunnable(), t2);
Thread t3 = new Thread(new MyRunnable(), t3);
t1.start();
//start second thread after waiting for 2 seconds or if it's dead
try {
t1.join(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
//start third thread only when first thread is dead
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
t3.start();
//let all threads finish execution before finishing main thread
try {
t1.join();
t2.join();
t3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(All threads are dead, exiting main thread);
}
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println(Thread started::: + Thread.currentThread.getName());
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread ended::: +Thread.currentThread.getName());
}
}
上述程序的輸出結果為:
Thread started:::t1
Thread started:::t2
Thread ended:::t1
Thread started:::t3
Thread ended:::t2
Thread ended:::t3
All threads are dead, exiting main thread