我想知道为什么线程会自发地从 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();
}
}
即使条件仅从
false
到 true
。
最佳答案
这些自发唤醒也称为“虚假唤醒”。在 Java 规范中,jvm 实现允许(尽管不鼓励)虚假唤醒。
允许它们的原因是因为许多实现可能基于具有这种行为的 pthreads(POSIX 线程)。为什么?
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/