问题来源
如下测试代码,输出的结果是主线程等待子线程 t 执行完成后,才会打印test,这是为什么?
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
System.out.println("t start");
try {
// 等待2秒
Thread.sleep(2000);
// System.out.println(Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("t end");
});
t.start();
t.join();
// System.out.println(Thread.currentThread().getName());
System.out.println("test");
}
输出为
t start
t end
test
原因分析(Thread的源码)
Thread在join方法中调用了自己的join(long timeout)join(long timeout)
方法。
public final void join() throws InterruptedException {
join(0);
}
在这里需要先说明一下wait方法的作用:
wait的作用是释放对象锁,释放CUP资源,使当前线程阻塞,进入对象的wait set,直到被通知、被中断或timeout到期。
当前线程指的是调用t.wait(0)方法的线程,很显然是主线程调用的t.join(),进而调用的t.wait(0),所以join是阻塞主(父)线程,而非子线程。
这里将子线程的变量名从 t 换成 o会更好理解,子线程对象在调用wait(0)的时候是以一个普通对象的身份,而非线程。
/**
* Waits at most {@code millis} milliseconds for this thread to
* die. A timeout of {@code 0} means to wait forever.
*
* <p> This implementation uses a loop of {@code this.wait} calls
* conditioned on {@code this.isAlive}. As a thread terminates the
* {@code this.notifyAll} method is invoked. It is recommended that
* applications not use {@code wait}, {@code notify}, or
* {@code notifyAll} on {@code Thread} instances.
*
* @param millis
* the time to wait in milliseconds
*
* @throws IllegalArgumentException
* if the value of {@code millis} is negative
*
* @throws InterruptedException
* if any thread has interrupted the current thread. The
* <i>interrupted status</i> 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相当于 this.wait(0)
// 也相当于 t.wait(0)
wait(0);
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
何时唤醒?
关于何时主线程会被唤醒这个问题的答案,不在 jdk 的源码中,而是在 jvm 源码中。本人暂时还没研究这么深,惭愧。但从 join 方法的注释中可以找到一点线索:As a thread terminates the {@code this.notifyAll} method is invoked,当线程终止时,this.notifyAll
方法会被调用。