2
我有一个静态信号量实例。Java中的信号量。为什么第二个线程不在等待?
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秒的延迟打印,但是当我运行此代码时,立即打印所有三个值。为什么?
我错过了什么?
谢谢。我需要在获取和释放之间切换。然后它完美地工作。 –
或者只是使用更直观的ReentrantLock。 lock()和unlock()完全符合你认为他们做的事。 – Matt