join
public final void join(long millis,
int nanos)
throws InterruptedException
-
等待该线程终止的时间最长为
millis 毫秒 +
nanos 纳秒。
-
参数:
-
millis - 以毫秒为单位的等待时间。
-
nanos - 要等待的 0-999999 附加纳秒。
抛出:
-
IllegalArgumentException - 如果 millis 值为负,则 nanos 的值不在 0-999999 范围内。
-
InterruptedException - 如果任何线程中断了当前线程。当抛出该异常时,当前线程的
中断状态 被清除
join
public final void join(long millis)
throws InterruptedException
-
等待该线程终止的时间最长为
millis 毫秒。超时为
0 意味着要一直等下去。
-
参数:
-
millis - 以毫秒为单位的等待时间。
抛出:
-
InterruptedException - 如果任何线程中断了当前线程。当抛出该异常时,当前线程的
中断状态 被清除。
join
public final void join()
throws InterruptedException
-
等待该线程终止。
-
抛出:
-
InterruptedException - 如果任何线程中断了当前线程。当抛出该异常时,当前线程的
中断状态 被清除
-
==========================================================
-
如果想要一个线程的启动在另一个线程执行完之后再启动,或者在另一个线程启动指定时间后再启动就可以用join方法来调度.
-
下面为一个例子:
-
public class MyRunnable implements Runnable {
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
System.out.println("Thread started :" + Thread.currentThread().getName() + "...");
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Thread ended:::"+Thread.currentThread().getName());
}
}
public class ThreadJoinExample {
/**
* @author congquan.zhou
* @date 2014-3-14
* @param args
*/
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable(),"t1");
Thread t2 = new Thread(new MyRunnable(),"t2");
Thread t3 = new Thread(new MyRunnable(),"t3");
t1.start();
try {
t1.join(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t2.start();
try {
t1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t3.start();
try {
t1.join();
t2.join();
t3.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("All threads are dead,exiting main thread");
}
}