2012-06-21 29 views
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秒的延迟打印,但是当我运行此代码时,立即打印所有三个值。为什么?

我错过了什么?

回答

3

A new Semaphore(1)1最初的许可证,因此允许一个立即acquire通过。此外,由于release总是允许两个线程立即进行,所以总是

要强制一件事发生在另一件事之前,您可以使用new Semaphore(0)。这将强制线程调用acquire等待执行线程release

+0

谢谢。我需要在获取和释放之间切换。然后它完美地工作。 –

+2

或者只是使用更直观的ReentrantLock。 lock()和unlock()完全符合你认为他们做的事。 – Matt