ManualResetEvent

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 boolean waitOne(long milliseconds) throws InterruptedException {
    synchronized (monitor) {
      if (open) 
        return true;
      monitor.wait(milliseconds);
        return open;
    }
  }

  public void set() {//open start
    synchronized (monitor) {
      open = true;
      monitor.notifyAll();
    }
  }

  public void reset() {//close stop
    open = false;
  }
}

 

  • @LimitedAtonement:在Java中,您必须处于同步块中才能等待对象.在等待期间,该对象的监视器锁定被释放,因此可以在另一个线程中获取.请参阅http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html

你可能感兴趣的:(JAVA经验)