Another monitor sample

public class TTT {
  public static void main (String [] args) {
    X x = new X();
    new Thread(new Waiter(x)).start();
    new Thread(new Waiter(x)).start();
    new Thread(new Notifier(x)).start();
  }
}

class X {
  synchronized void w() throws InterruptedException {
    before(); wait(); after();
  }
  synchronized void n() { notifyAll(); }
  void before() {}
  void after() {}
}

class Waiter implements Runnable {
  private X x;
  public Waiter(X x) {
    this.x = x;
  }
  @Override
  public void run() {
    try {
      x.w();
    } catch (InterruptedException ex) {
      ex.printStackTrace();
    }
  }
}

class Notifier implements Runnable {
  private X x;
  public Notifier(X x) {
    this.x = x;
  }
  @Override
  public void run() {
    x.n();
  }
}
 

你可能感兴趣的:(thread)