Object.wait
的 javadoc提及,
As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop.
synchronized (obj) {
while (<condition does not hold>) {
obj.wait(timeout, nanos);
}
... // Perform action appropriate to condition
}
这里没有提到需要处理 InterruptedException
。
这是否意味着 wait 方法可能会在不抛出一个的情况下自发唤醒。
我环顾四周,但没有发现任何关于实际如何处理唤醒的具体信息。
由于虚假中断不是一回事(或者我已经读过),我相信情况就是如此。我只是在寻找对此的确认。
最佳答案
通常 obj.wait(...)
应该等到有人调用 obj.notify()
(或直到达到超时),但正如文档所述:
A thread can wake up without being notified, interrupted, or timing out, a so-called spurious wakeup. While this will rarely occur in practice, applications must guard against it by testing for the condition that should have caused the thread to be awakened, and continuing to wait if the condition is not satisfied. See the example below
由于虚假唤醒,线程可能会在未收到通知的情况下唤醒。这就是为什么必须在循环中检查监视器的保护条件(示例也取自 javadoc):
synchronized (obj) {
while (<condition does not hold> and <timeout not exceeded>) {
long timeoutMillis = ... ; // recompute timeout values
int nanos = ... ;
obj.wait(timeoutMillis, nanos);
}
... // Perform action appropriate to condition or timeout
}
如果您正在使用超时,您应该检查是否也超过了超时。
这与处理中断异常无关。那些不会被虚假地抛出,但前提是当前线程真的被中断了。那是在您的 spurious 循环中,您不需要为 InterruptedException
关于java - spurios 唤醒是否伴随着 InterruptedException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57787946/