如果我们在等待之前立即使用通知会有什么不利之处

时间:2015-01-21 10:09:43

标签: wait notify

我正在阅读Java: notify() vs. notifyAll() all over again。 xagyg在那里给出了一个很好的例子。我只是想知道如果我在下面等待之前立即发出通知,它会解决死锁问题吗?请解释一下。

while (buf.size()==MAX_SIZE) {
      notify();
      wait(); // called if the buffer is full (try/catch removed for brevity)

}

while (buf.size()==0) {
    notify();
    wait(); // called if the buffer is empty (try/catch removed for brevity)
    // X: this is where C1 tries to re-acquire the lock (see below)
}

1 个答案:

答案 0 :(得分:0)

我想我明白了,如果我们先通知那么所有线程都可能会被唤醒并尝试访问同步函数但是因为等待没有被调用所以它仍然被锁定。锁定将仅通过调用wait来释放,因此它将再次陷入僵局。