java无限等待问题?

标签 java synchronization wait

代码1:

  class BCWCExamples  {
    public Object lock;

    boolean someCondition;

    public void NoChecking() throws InterruptedException {
        synchronized(lock) {
            //Defect due to not checking a wait condition at all
            lock.wait();  
        }
    }

代码2:

 public void IfCheck() throws InterruptedException {
            synchronized(lock) {
                // Defect due to not checking the wait condition with a loop. 
                // If the wait is woken up by a spurious wakeup, we may continue
                // without someCondition becoming true.
                if(!someCondition) { 
                    lock.wait();
                }
            }
        }

代码3:

public void OutsideLockLoop() throws InterruptedException {
            // Defect. It is possible for someCondition to become true after
            // the check but before acquiring the lock. This would cause this thread
            // to wait unnecessarily, potentially for quite a long time.
            while(!someCondition) {
                synchronized(lock) {
                    lock.wait();
                }
            }
        }

代码4:

public void Correct() throws InterruptedException {
            // Correct checking of the wait condition. The condition is checked
            // before waiting inside the locked region, and is rechecked after wait
            // returns.
            synchronized(lock) {
                while(!someCondition) {
                    lock.wait();
                }
            }
        }
    }    

注意:有其他地方的通知

代码1中没有等待条件,因此存在无限等待,但为什么其他3个代码(2,3,4)中发生无限等待
请检查代码中的注释以便更好地理解请帮助我,我是java等待和通知的新手

最佳答案

在您的示例中,我没有看到任何 lock.notify()lock.notifyAll() 调用。

简短的回答:您将wait()除非您在同一个对象lock上调用notify()

有关更多信息,请考虑查看下一个链接:

关于java无限等待问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41120182/

相关文章:

java - 使用 Java 中的 JsonPath 解析 JSON 中的数组

java - 等待通知和 CountDownLatch 之间的区别

html - 如何在css中添加元素之前等待一段时间? javascript?

Java Applet - 将文件转换为字符串

java - 如何在 Android Wifi 中列出相同的 SSID?

c# - 从 C# TCP 服务器到 Android 设备的图像传输

java - 使用装饰器的简单缓存机制

c - 在 C 中使用 mutex 和 barrier 进行线程同步

bash - 如何等待非子进程?

c++ - 无法为 Qt 的 waitForConnected 设置超时