notify() 而不是 notifyAll() 用于阻塞队列

我正在尝试找出是否可以有一个多生产者/多消费者队列,我可以在其中使用 notify() 而不是 notifyAll().例如,在下面的实现中(来源:here)你不能只只需将 notifyAll() 切换为 notify().为什么你不能切换并不完全清楚,所以我将把它作为一个预告片留给任何想帮助我理解这个问题的人.

I am trying to find out whether it is possible to have a multiple producer / multiple consumer queue where I can use notify() instead of notifyAll(). For example, in the implementation below (source: here) you cannot just simply switch the notifyAll() for notify(). It is not totally obvious why you cannot switch so I will leave it as an teaser to whoever wants to help me out understanding this problem.

所以下面的代码坏了:

public class BlockingQueue {

  private Object lock = new Object();

  private List queue = new LinkedList();
  private int  limit = 10;

  public BlockingQueue(int limit){
    this.limit = limit;
  }


  public void enqueue(Object item)
  throws InterruptedException  {
   synchronized(lock) {
    while(this.queue.size() == this.limit) {
      lock.wait();
    }
    if(this.queue.size() == 0) {
      lock.notify();
    }
    this.queue.add(item);
   }
  }


  public Object dequeue()
  throws InterruptedException{
   synchronized(lock) {
    while(this.queue.size() == 0){
      lock.wait();
    }
    if(this.queue.size() == this.limit){
      lock.notify();
    }

    return this.queue.remove(0);
  }
 }
}

推荐答案

以下步骤导致我们陷入僵局.让我们将 limit 设置为 1 以保持示例简短.

The following steps lead us to deadlock. Let's set limit to 1 to keep the example brief.

  • E1 将项目排入队列.
  • E2 尝试入队 - 检查等待循环 - 已满 - 等待
  • E3 尝试入队 - 检查等待循环 - 已满 - 等待

  • E1 enqueues an item.
  • E2 attempts enqueue - checks wait loop - already full - waits
  • E3 attempts enqueue - checks wait loop - already full - waits

D1 尝试出队 - 并且正在执行同步块

D1 attempts dequeue - and is executing synchronized block

D3 尝试出队 - 进入(同步)块时的块 - 由于 D1

D3 attempts dequeue - blocks on entry to the (synchronized) block - due to D1

D1 正在执行入队 - 获取项目,调用通知,退出方法

D1 is executing enqueue - gets the item, calls notify, exits method

D3在D2之后,E2之前进入block,检查等待循环,队列中没有更多的项目,所以等待

D3 enters block after D2, but before E2, checks wait loop, no more items in queue, so waits

现在有 E3、D2 和 D3 等待!

Now there is E3, D2, and D3 waiting!

最后E2获取锁,入队,调用notify,退出方法

Finally E2 acquires the lock, enqueues an item, calls notify, exits method

E2 的通知唤醒 E3(记住任何线程都可以被唤醒)

E2's notification wakes E3 (remember any thread can be woken)

解决方案:将 notify 替换为 notifyAll

相关文章