java - 为什么线程会自发地从 wait() 中唤醒?

标签 java concurrency multithreading

我想知道为什么线程会自发地从 java 中的 wait() 中唤醒。
这是一个设计决定吗?是妥协吗?

编辑:(来自 Java 并发实践,第 300 页)

wait is even allowed to return "spuriously" - not in response to any thread calling notify.

作者进一步指出:

this is like a toaster with a loose connection that makes the bell go off when the toast is ready but also sometimes when it is not ready.

这就是为什么你总是必须像这样编写代码的原因

synchronized(this){
    while(!condition)
        wait();
    }
}

永远不会

synchronized(this){
    if(!condition){
        wait();
    }
}

即使条件仅从 falsetrue

最佳答案

这些自发唤醒也称为“虚假唤醒”。在 Java 规范中,jvm 实现允许(尽管不鼓励)虚假唤醒。

允许它们的原因是因为许多实现可能基于具有这种行为的 pthreads(POSIX 线程)。为什么?

Wikipedia:

According to David R. Butenhof's Programming with POSIX Threads ISBN 0-201-63392-2: "This means that when you wait on a condition variable, the wait may (occasionally) return when no thread specifically broadcast or signalled that condition variable. Spurious wakeups may sound strange, but on some multiprocessor systems, making condition wakeup completely predictable might substantially slow all condition variable operations. The race conditions that cause spurious wakeups should be considered rare."

关于java - 为什么线程会自发地从 wait() 中唤醒?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2540984/

相关文章:

Java同步-不正确的发布

java - 在多核集群节点上并行运行 java 应用程序

Java:重新设计开源库的并发性

java - 套接字异常 : Connection closed by remote host when pushing to producation destination

java - FileOutputStream - 有时写入数据,有时不写入

java - 如何将 MS Word HTML 文档转换为干净的 XHTML 内联样式?

c# - "A commit is already in progress"试图在 Telerik OpenAccess ORM 中保存更改

java - Java中如何并发执行同一个方法

c# - 下面类线程安全吗?解释

java - Websphere JAVA_DUMP_OPTS 条件捕获的所有事件有哪些?