Thread类join()方法重载了3次.分别是
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的线程不死亡,程序就会阻塞在那里.
实例:现在有T1、T2、T3三个线程,你怎样保证T2在T1执行完后执行,T3在T2执行完后执行?
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(); } }
终端输出
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
时间: 2024-11-04 09:10:42