java 信号量简单示例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9868363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Semaphore simple sample
提问by user1074896
Can anyone share simple sample of using Semaphore? If it's possible a sample of solving a task without semaphore and then with semaphore to understand main idea of it.
任何人都可以分享使用信号量的简单示例吗?如果有可能在没有信号量的情况下解决任务的示例,然后使用信号量来理解它的主要思想。
回答by CloudyMarble
Here is a simple Semaphore implementation:
这是一个简单的信号量实现:
public class Semaphore {
private boolean signal = false;
public synchronized void take() {
this.signal = true;
this.notify();
}
public synchronized void release() throws InterruptedException{
while(!this.signal) wait();
this.signal = false;
}
}
The take()
method sends a signal which is stored internally in the Semaphore. The release()
method waits for a signal. When received the signal flag is cleared again, and the release()
method exited.
该take()
方法发送一个信号,该信号存储在信号量内部。该release()
方法等待信号。当接收到信号标志时再次清除,并release()
退出该方法。
Read this articleand take a look at this example