Java Equivalent of .NET's ManualResetEvent and WaitHandle

前端 未结 4 1239
野趣味
野趣味 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:06

    class ManualResetEvent {
    
      private final Object monitor = new Object();
      private volatile boolean open = false;
    
      public ManualResetEvent(boolean open) {
        this.open = open;
      }
    
      public void waitOne() throws InterruptedException {
        synchronized (monitor) {
          while (open==false) {
              monitor.wait();
          }
        }
      }
    
      public void set() {//open start
        synchronized (monitor) {
          open = true;
          monitor.notifyAll();
        }
      }
    
      public void reset() {//close stop
        open = false;
      }
    }
    

提交回复
热议问题