Java - NotifyAll 而不是 BoundedSemaphore 实现中的通知

问题描述 投票:0回答:1

Jenkov 网站上找到的 BoundedSemaphore 示例实现 在 take 和release 方法中使用了notify 而不是notifyall。在具有多个消费者和生产者的场景中,这是否会导致生产者唤醒另一个生产者(同样消费者线程可能会唤醒另一个消费者线程)从而导致信号丢失? notifyall 更有意义还是我错过了什么?

public class BoundedSemaphore {
  private int signals = 0;
  private int bound   = 0;

  public BoundedSemaphore(int upperBound){
    this.bound = upperBound;
  }

  public synchronized void take() throws InterruptedException{
    while(this.signals == bound) wait();
    this.signals++;
    this.notify();
  }

  public synchronized void release() throws InterruptedException{
    while(this.signals == 0) wait();
    this.signals--;
    this.notify();
  }
}

生产者/消费者模式使用notifyall来避免一个消费者唤醒另一个消费者的问题。我期望示例代码使用notifyall而不是notify

java multithreading semaphore counting-semaphore
1个回答
0
投票

你担心的情况永远不会发生。

例如:当

take
呼叫
notify
时,不可能有另一个
take
wait
等待。因为如果确实如此,则意味着
this.signals == 0
并且如果第一个线程调用
notify
是不可能的。

© www.soinside.com 2019 - 2024. All rights reserved.