我有一个静态信号量实例。
Semaphore semaphore = new Semaphore(1);
现在我有两个线程(发送线程和接收线程)
发送主题:
public class SendingThread implements Runnable {
private Semaphore semaphore;
public SendingThread(Semaphore semaphore){
this.semaphore = semaphore;
}
@Override
public void run() {
try {
System.out.println("1");
Thread.sleep(4000);
this.semaphore.acquire();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
}
}
}
和接收线程:
public class RecievingThread implements Runnable {
private Semaphore semaphore;
public RecievingThread(Semaphore semaphore){
this.semaphore = semaphore;
}
@Override
public void run() {
System.out.println("2");
this.semaphore.release();
System.out.println("3");
}
}
当我根据我的理解启动这2个线程时,接收线程将等待 4秒直到
发送线程将通知它接收线程可以继续。这意味着 System.out.println("3");
将延迟 4 秒打印,但当我运行此代码时,所有三个值都会立即打印。为什么?
我错过了什么吗?
最佳答案
新信号量(1)
具有1个初始许可,因此允许立即获取
通过。此外,由于release
总是允许两个线程立即继续。
要强制一件事在另一件事之前发生,您可以使用new Semaphore(0)
。这将强制调用acquire
的线程等待执行release
的线程。
关于java - Java 中的信号量。为什么第二个线程不等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11147682/