【问题标题】:java infinite wait issue? [closed]java无限等待问题? [关闭]
【发布时间】:2016-12-13 11:37:42
【问题描述】:

代码 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)
请检查代码中的 cmets更好的理解请帮助我我是java新手等待并通知

【问题讨论】:

  • 这就是相关代码的全部吗?值 someCondition 永远不会设置为 true

标签: java synchronization wait


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2014-11-23
    • 2020-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多