如何实现信号量
how to implement of semaphore
我正在经历 this link ,这里给出了计数信号量的实现:
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() 方法中,调用通知,这将使其他线程进入 section.Shouldnt 在 take 方法中等待。请帮助我理解。
谢谢
贾延德拉
使用java.util.concurrent.Semaphore
.
A counting semaphore. Conceptually, a semaphore maintains a set of permits. Each acquire() blocks if necessary until a permit is available, and then takes it. Each release() adds a permit, potentially releasing a blocking acquirer. However, no actual permit objects are used; the Semaphore just keeps a count of the number available and acts accordingly.
该文章的第一条评论指出:
Don't you have "take" and "release" reversed?
作者承认
You are right, that should probably have been reversed.
所以,是的,it seems the article got things mixed up a bit。
如果你只是切换这两种方法,它可能会起作用。
然而,在现实生活中,JDK 现在在并发实用程序包中有信号量,您应该使用它们。
至于了解事物是如何工作的,首先查看 JDK 源代码可能有点挑战(但在您初步理解之后阅读是非常好的)。最好能找到更好的文章。
方法名被翻译错误调换了,见原作者的评论。这种形式的代码没有意义,因为它会产生死锁:释放只会在计数器为零时减少计数器,这种情况不会再发生!
如果交换调用,即通过调用 'release' 锁定,信号量将起作用,但不计数。
我正在经历 this link ,这里给出了计数信号量的实现:
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() 方法中,调用通知,这将使其他线程进入 section.Shouldnt 在 take 方法中等待。请帮助我理解。
谢谢
贾延德拉
使用java.util.concurrent.Semaphore
.
A counting semaphore. Conceptually, a semaphore maintains a set of permits. Each acquire() blocks if necessary until a permit is available, and then takes it. Each release() adds a permit, potentially releasing a blocking acquirer. However, no actual permit objects are used; the Semaphore just keeps a count of the number available and acts accordingly.
该文章的第一条评论指出:
Don't you have "take" and "release" reversed?
作者承认
You are right, that should probably have been reversed.
所以,是的,it seems the article got things mixed up a bit。
如果你只是切换这两种方法,它可能会起作用。
然而,在现实生活中,JDK 现在在并发实用程序包中有信号量,您应该使用它们。
至于了解事物是如何工作的,首先查看 JDK 源代码可能有点挑战(但在您初步理解之后阅读是非常好的)。最好能找到更好的文章。
方法名被翻译错误调换了,见原作者的评论。这种形式的代码没有意义,因为它会产生死锁:释放只会在计数器为零时减少计数器,这种情况不会再发生!
如果交换调用,即通过调用 'release' 锁定,信号量将起作用,但不计数。