Java Equivalent of .NET's ManualResetEvent and WaitHandle

前端 未结 4 1240
野趣味
野趣味 2020-12-11 15:21

I would like to know if Java provides an equivalent of .NET\'s classes of ManualResetEvent and WaitHandle, as I would like to write code that blocks for a given timeout unle

4条回答
  •  醉话见心
    2020-12-11 16:09

    From: http://www.experts-exchange.com/Programming/Languages/Java/Q_22076798.html

    Hi, you can achieve synchronization using the java.util.concurrent.Semaphore class (use 0 permit).

    http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Semaphore.html

    Example below shows you how to solve the first sync problem, the other will be similar:

    import java.util.concurrent.Semaphore;
    
    class ScalesCommunication {
    
       private static Semaphore sem = new Semaphore(0);
    
       // called by thread 1
       void readLoop() {
          //...
    
          //after connection established, release semaphore (value incremented by 1)
          sem.release();
       }
    
       // called by thread 2
       String sendCommand(String command) {
    
           sem.acquire(); // thread waits here if sem value == 0
    
           // at this point connection is established
           //...
       }
    }
    

提交回复
热议问题