【问题标题】:JDK implementation of Thread.join()Thread.join() 的 JDK 实现
【发布时间】: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


【解决方案1】:

notifyAll(或其本机等效项)在当前版本的第 1526 行 src/share/vm/runtime/thread.cpp 的 ensure_join 中调用,该版本是从同一文件中的 JavaThread::exit 调用的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    • 1970-01-01
    • 2019-08-09
    • 1970-01-01
    • 2015-09-06
    • 2015-08-09
    • 2015-08-25
    相关资源
    最近更新 更多