javadoc是这样写的
public final void join()
throws InterruptedExceptionWaits for this thread to die.
An invocation of this method behaves in exactly the same way as the invocation
join(0)
Throws:
InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.
可以看到这是一个阻塞方法,并且可以响应中断。
join()方法实现大致是使用了一个while循环一直判断当前线程是否存活,如果存活的话,调用wait()方法,使线程进入WAITING状态;当线程终止时,jvm会自动调用它的notifyAll()方法(在jdk源码中看不到,应该在jvm源码中),将其唤醒,此时isAlive方法返回false,方法执行完成。
相当于把一个线程对象当做监视器锁用了。
同时join(long)方法还可以传入一个超时等待时间,避免过长时间的阻塞。
此方法的实现如下:
public final void join() throws InterruptedException {
join(0);
}
public final void join(long millis)
throws InterruptedException
Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever.
This implementation uses a loop of this.wait calls conditioned on this.isAlive. As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.
Parameters:
millis - the time to wait in milliseconds
Throws:
IllegalArgumentException - if the value of millis is negative
InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.
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;
}
}
}