如果线程A执行了Thread.join()方法,那么线程A等待Thread线程终止之后才从Thread.join()返回。
Thread.join(millis)具备超时特性的方法,如果线程Thread在给定的超时时间里没有终止,那么将会从超时方法中返回。
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 Domino(previous), String.valueOf(i));
thread.start();
previous = thread;
}
TimeUnit.SECONDS.sleep(1);
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");
}
}
}
/* * Thread0必须等到Main方法终止后才能继续执行打印语句。 * Thread1必须等到Thread0终止后才能继续执行打印语句。 * ..... * Main线程中创建了10个线程,它们在执行到join方法时都进入Waiting状态。 * 当Main线程执行完后,它们一次从Waiting变为运行状态。 *
join()方法涉及到 等待/通知机制(等待前驱线程结束,接受前驱线程结束通知)
public final synchronized void join(long millis)
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {//等待时间小于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的线程是否存活,如果存活,让当前线程永远等待。
wait(0):永远等待。
暑期编程PK赛 得CSDN机械键盘等精美礼品!


