本文介绍了Java - notify()vs notifyAll() - 可能的死锁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何情况下 notify()可能导致死锁,但 notifyAll() - never? / p>

例如,在多个锁的情况下。 notify()只通知一个线程运行,它检查对某个对象的锁定,并再次等待,虽然另一个线程可以解锁该对象。在使用 notifyAll()的情况下,所有线程都会被通知运行,而其中一个线程会依次解锁该对象。

解决方案

是的。想象一下,您可以使用同步,等待和通知来实现生产者 - 消费者问题。 (编辑)其中,2个制片人和2个消费者都在同一对象监视器上等待(结束编辑)。生产者调用通知在这个实现。现在假设你有两个Threads运行生产者的代码路径。 Producer1调用 notify 可能会唤醒Producer2。 Producer2意识到他不能做任何工作,随后未能调用 notify

(编辑)已调用 notifyAll 除了Producer2之外,Consumer1和Consumer2都会被唤醒。其中一个消费者会消耗这些数据,然后调用 notifyAll 来唤醒至少一个生产者,从而允许非常坏的实现成功地失败。



这是我的场景的参考问题:


Is there any situation in which notify() can cause deadlock, but notifyAll() - never?

For example, in case of multiple locks. notify() notifies only one thread to run, which checks for lock to some object and becomes waiting again, though another thread could unlock that object. In case of using notifyAll(), all threads will be notified to run and one of them in its turn will unlock that object for sure.

解决方案

Yes. Imagine you implement the Producer - Consumer problem with synchronize, wait, and notify. (edit) In which 2 Producers and 2 Consumers all wait on the same object monitor (end edit).The Producer calls notify in this implementation. Now suppose you have two Threads running the Producer's code path. It is possible that Producer1 calls notify and wakes Producer2. Producer2 realizes he can not do any work and subsequently fails to call notify. Now you are deadlocked.

(edit) Had notifyAll been called, then both Consumer1 and Consumer2 would have woken up in addition to Producer2. One of the Consumers would have consumed the data and in turn called notifyAll to wake up at least one Producer, thus allowing the very broken implementation to limp along successfully.

Here is the reference question I base my scenario off of:http://stackoverflow.com/questions/3067877/my-produce-consumer-hangs

这篇关于Java - notify()vs notifyAll() - 可能的死锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 09:18