如果一个线程A执行了thread.join()语句,其含义是:当前线程A等待thread线程终止之后才从thrad.join()返回。线程thread除了提供join()方法之外,还提供了join(long millis)和join(long millis,int nanos)两个具备超时特性的方法。这两个超时方法表示,如果线程thread在给定的超时时间里没有终止,那么将会从该方法中返回。
如下例子,创建了10个线程,编号0~9,每个线程调用前一个线程的join()方法,也就是线程0结束了,线程1才能从join()方法中返回,而线程0需要等待main线程结束。
public class JoinTest {
public static void main(String[] args) throws InterruptedException {
Thread previous = Thread.currentThread();
for (int i = 0; i <10; i++) {
//每个线程拥有前一个线程的引用,需要等待前一个线程终止,才能从等待中返回
Thread thread = new Thread(new Demo(previous),String.valueOf(i));
thread.start();
previous=thread;
}
//主线程也就是第一个父线程休眠5秒
TimeUnit.SECONDS.sleep(5);
System.out.println(Thread.currentThread().getName()+" terminate.");
}
static class Demo implements Runnable{
private Thread thread;
public Demo(Thread thread) {
this.thread = thread;
}
@Override
public void run() {
try {
//thread线程终止之后才会继续执行
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" terminate.");
}
}
}
运行程序结果如下
main terminate.
0 terminate.
1 terminate.
2 terminate.
3 terminate.
4 terminate.
5 terminate.
6 terminate.
7 terminate.
8 terminate.
9 terminate.
结果跟预想的一致。