调用thread.join()方法的线程,需要等待thread完成后才能继续执行代码。
例子:线程main和Thread-0~1依次等待前一个线程完成后,才能继续执行join()方法之后的代码。
package com.join;
import java.util.concurrent.TimeUnit;
public class Join {
public static void main(String[] args) throws InterruptedException {
Thread previous = Thread.currentThread();
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(new Recurse(previous), "Thread-" + i);
thread.start();
previous = thread;
}
TimeUnit.SECONDS.sleep(4);
System.out.println("Thread-" + Thread.currentThread().getName() + " is terminated.");
}
static class Recurse implements Runnable {
private Thread thread;
public Recurse(Thread thread) {
this.thread = thread;
}
@Override
public void run() {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " is terminated.");
}
}
}