java - 为什么等待循环条件在多线程上下文中是安全的?

标签 java multithreading

我很难真正理解它是如何工作的:

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),并且只相对于其他同步访问该对象。如果您的条件取决于不同的对象,或者您在其他地方没有同步地访问该对象,那么事情可能会变糟。因此,不要那样做。


同样的道理也适用于 LockCondition 的使用。 See this code sample.条件变量派生自锁对象,synchronized/wait/notify类比于lock;解锁/等待/信号

关于java - 为什么等待循环条件在多线程上下文中是安全的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30381522/

相关文章:

r - 具有 0 值的 R 矩阵单元格需要多少空间?以及如何处理大矩阵计算

java - 如何仅使用一个代码库对多个容器使用多种配置?

java - 使用java中的DAL在数据库中插入和更新值

java - 扩展 Log4j Logger 类时出现 NullPointerException

java - 准备语句的空结果集

java - 同时中断多个线程

python - python中setInterval的等价物

multithreading - Rayon 会避免为少量工作生成线程吗?

java - Android/Java 试图找出放置变量声明的位置

java - MulticastSocket 加入/离开组、发送、接收线程安全