【问题标题】:Why in this code, the semaphore counts up instead of down?为什么在这段代码中,信号量是向上计数而不是向下计数?
【发布时间】:2014-10-02 16:48:40
【问题描述】:

我正在http://tutorials.jenkov.com/java-concurrency/semaphores.html阅读本教程

它的计数信号量实现是:

public class CountingSemaphore {
  private int signals = 0;

  public synchronized void take() {
    this.signals++;
    this.notify();
  }

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

}

代码对我来说似乎很奇怪,因为据我了解,信号量记录有多少可用资源,所以我们应该在 take() 时减少计数,在 release() 时增加计数(当然从一个限制)。

谁能让我更深入地了解计数方法和倒计数方法之间的区别?

【问题讨论】:

  • 整个 take/release 是倒退的 - release 应该通知,而不是等待。是的,计数也是倒数。我建议你联系作者。

标签: java synchronization locking mutex semaphore


【解决方案1】:

到这里,好像很明显两个方法的代码已经互换了,应该是

public class CountingSemaphore {
  private int signals = 0;

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

  public synchronized void release() {
     this.signals++;
     this.notify();
  }    
}

确实,阻塞方法是take而不是release,可以任意调用次数。

更一般地说,向上计数似乎很自然,但理论上也可以完全相反。不确定它是否有用(并且可读)!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 2011-01-16
    • 1970-01-01
    • 2021-09-02
    • 2013-03-04
    • 1970-01-01
    • 2020-09-09
    相关资源
    最近更新 更多