Thread.join()语句的含义:当前线程A等待thread线程终止之后才从thred.join()返回。
下面例子里, 创建了10个线程,编号0~9,每个线程调用前一个线程join()方法,也就是线程0结束了,线程1才能从join()方法中返回,而线程0需要等待main线程结束。
代码语言:javascript复制package cn.com.test;
import java.util.concurrent.TimeUnit;
public class Join {
public static void main(String[] args) throws Exception {
Thread previous = Thread.currentThread();
for (int i = 0; i < 10; i ) {
// 每个线程拥有前一个线程的引用,需要等待前一个线程终止,才能从等待中返回
Thread thread = new Thread(new Domino(previous), String.valueOf(i));
thread.start();
previous = thread;
}
TimeUnit.SECONDS.sleep(5);
System.out.println(Thread.currentThread().getName() " terminate.");
}
static class Domino implements Runnable {
private Thread thread;
public Domino(Thread thread) {
this.thread = thread;
}
public void run() {
try {
thread.join();
} catch (InterruptedException e) {
// TODO: handle exception
}
System.out
.println(Thread.currentThread().getName() " terminate.");
}
}
}
输出结果如下:
代码语言:javascript复制main terminate.
0 terminate.
1 terminate.
2 terminate.
3 terminate.
4 terminate.
5 terminate.
6 terminate.
7 terminate.
8 terminate.
9 terminate.
关于线程是怎么从join()中返回的没看懂,先码下来再说。