Thread.join()
如果一个线程A执行了Thread.join()方法,含义是,当前线程A等待Thread线程终止
之后才从Thread.join()返回。线程Thread除了Thread.join(),还有Thread.join(long millis)和Thread.join(long millis, int nanos)两个具备超时特性
的方法。表示如果线程thrad在给定时间内没有终止
,那么将会从超时方法中返回
。
import java.util.concurrent.TimeUnit;
public class MyThread06 {
public static void main(String[] args) throws InterruptedException {
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;
}
@Override
public void run() {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "terminate.");
}
}
}
// 输出结果如下
// mainterminate.
// 0terminate.
// 1terminate.
// 2terminate.
// 3terminate.
// 4terminate.
// 5terminate.
// 6terminate.
// 7terminate.
// 8terminate.
// 9terminate.
从代码中看出,每个线程终止都依赖于前驱线程的终止,每个线程等待前驱线程终止后,从join()中返回,这里设计的等待/通知机制,即等待前驱线程结束,接受前驱线程结束通知
下面是join方法的源码
public final void join() throws InterruptedException {
join(0);
}
public final synchronized void join(long millis) throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (millis == 0) {
while (isAlive()) {
wait(0);
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
我们发现,join()方法的逻辑结构和等待通知的方法一致,即加锁、循环和处理3个步骤。