package day1;
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 < 5; i++) {
// 每个线程拥有前一个线程的引用,需要等待前一个线程终止,才能从等待中返回
Thread thread = new Thread(new JoinDemo(previous), String.valueOf(i));
thread.start();
previous = thread;
}
TimeUnit.SECONDS.sleep(5);
System.out.println(Thread.currentThread().getName() + " terminate.");
}
static class JoinDemo implements Runnable {
private Thread thread;
public JoinDemo(Thread thread) {
this.thread = thread;
}
public void run() {
try {
thread.join();
} catch (InterruptedException e) {
}
System.out.println(Thread.currentThread().getName() + " terminate.");
}
}
}
console输出:
main terminate.
0 terminate.
1 terminate.
2 terminate.
3 terminate.
4 terminate.
join:thread.join()方法,当前线程会等待调用线程执行完,再继续执行