我正在阅读本教程: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()
时增加计数(当然从限制开始)。
任何人都可以让我更深入地了解向上计数和向下计数方法之间的区别吗?
最佳答案
这里,显然两个方法的代码已经互换了,应该是
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
,它可以被调用任意多次。
更一般地说,向上计数似乎很自然,但理论上也可以做完全相反的事情。但不确定它是否有用(且可读)!
关于java - 为什么在这段代码中,信号量是向上计数而不是向下计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26165587/