Thread類join()方法重載了3次.分別是java
join()throws InterruptedException; //無參數的join()等價於join(0),做用是一直等待該線程死亡
join(long millis, int nanos) throws InterruptedException; //最多等待該線程死亡millis毫秒
join(long millis, int nanos) throws InterruptedException ; //最多等待該線程死亡millis毫秒加nanos納秒
join()的做用其實java doc 說的很清楚了:Waits for this thread to die.翻譯過來就是等待這個線程死亡,若是join的線程不死亡,程序就會阻塞在那裏.ide
實例:如今有T一、T二、T3三個線程,你怎樣保證T2在T1執行完後執行,T3在T2執行完後執行?this
import java.util.Date; class RunnableJob implements Runnable { @Override public void run() { Thread thread = Thread.currentThread(); System.out.println(thread.getName() + " start" + " at " + new Date()); try { Thread.sleep(1000); System.out.println(thread.getName() + " end" + " at " + new Date()); } catch (InterruptedException e) { e.printStackTrace(); } } } public class BasicTest { public static void main(String[] args) throws InterruptedException { //初始化 RunnableJob runnableJob = new RunnableJob(); Thread T1 = new Thread(runnableJob, "T1"); Thread T2 = new Thread(runnableJob, "T2"); Thread T3 = new Thread(runnableJob, "T3"); //T2在T1執行完後執行,T3在T2執行完後執行 T1.start(); T1.join(); T2.start(); T2.join(); T3.start(); } }
終端輸出spa
T1 start at Fri Sep 05 16:24:12 CST 2014 T1 end at Fri Sep 05 16:24:13 CST 2014 T2 start at Fri Sep 05 16:24:13 CST 2014 T2 end at Fri Sep 05 16:24:14 CST 2014 T3 start at Fri Sep 05 16:24:14 CST 2014 T3 end at Fri Sep 05 16:24:15 CST 2014