我很难真正理解它是如何工作的:
while(<some condition>){
wait();
}
OR this example:
while(<some condition>){
condition.await();
}
当线程已经通过 <some condition>
,
这可能真的发生了,<some condition>
已经false
什么时候wait()
或 await()
执行。
所以 wait()
或 await()
可以用已经无效的条件调用 - 这意味着意图被破坏。
我的逻辑有什么问题?
最佳答案
来自docs对于 wait()
:
The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.
(强调我的)
换句话说,如果没有 synchronized
block ,您的代码将抛出 IllegalMonitorStateException
。 与 synchronized
另一方面,您的条件将通过 wait();
调用自动检查。
这并不自动意味着你没有问题,因为这里的“原子地”只是关于你正在同步的对象(在你的情况下 this
),并且只相对于其他同步访问该对象。如果您的条件取决于不同的对象,或者您在其他地方没有同步地访问该对象,那么事情可能会变糟。因此,不要那样做。
同样的道理也适用于 Lock
和 Condition
的使用。 See this code sample.条件变量派生自锁对象,synchronized
/wait
/notify
类比于lock
;解锁
/等待
/信号
。
关于java - 为什么等待循环条件在多线程上下文中是安全的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30381522/