【发布时间】:2014-04-25 02:17:13
【问题描述】:
我想知道 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() 的位置,而不是在我们的代码中。
谢谢。
【问题讨论】:
-
它是 JDK 线程实现的一部分。当
run返回时,它相当于调用notifyAll。 -
它在本机代码中的某处被调用(用 c++ 编写)
标签: java multithreading concurrency jvm