我想知道 Java 是如何实现 join() 方法来等待线程完成的。根据source code :
public final synchronized void [More ...] 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;
}
}
}
调用线程在第 1160 行无限期地获取运行线程的监视器和 wait(),同时运行线程仍然存在。
我的问题是:当线程完成时,notify() 或 notifyAll() 在哪里(以及谁调用),以便它唤醒调用线程?
非常清楚,问题是关于在 JDK/JVM 中 调用 notify() 的位置,而不是在我们的代码中。
谢谢。
最佳答案
在 src/share/vm/runtime/thread.cpp 中的 ensure_join 中调用了 notifyAll(或其 native 等效项) ,在当前版本的第 1526 行,从同一文件中的 JavaThread::exit 调用。
关于java - Thread.join() 的 JDK 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22495652/