Using Wait() and Notify() to Control Access to a Shared Resource : Wait Notify « Thread « SCJP






class MainClass{
  public static void main(String args[]) {
    Resource resource = new Resource();
    Thread consumer = new Thread(new Consumer(resource));
    Thread[] producer = new Thread[3];
    for (int i = 0; i < producer.length; ++i)
      producer[i] = new Thread(new Producer(i, resource));
    consumer.start();
    for (int i = 0; i < producer.length; ++i)
      producer[i].start();
    boolean alive;
    out: do {
      alive = false;
      for (int i = 0; i < producer.length; ++i)
        alive |= producer[i].isAlive();
      Thread.currentThread().yield();
    } while (alive);
    consumer.interrupt();
  }
}

class Resource {
  boolean okToSend = false;

  public synchronized void displayOutput(int id, String[] message) {
    try {
      while (!okToSend) {
        wait();
      }
      okToSend = false;
      for (int i = 0; i < message.length; ++i) {
        Thread.currentThread().sleep(1000);
        System.out.println(id + ": " + message[i]);
      }
    } catch (InterruptedException ex) {
    }
  }

  public synchronized void allowOutput() {
    okToSend = true;
    notify();
  }
}

class Consumer implements Runnable {
  Resource resource;

  public Consumer(Resource resource) {
    this.resource = resource;
  }

  public void run() {
    try {
      while (true) {
        Thread.currentThread().sleep(1000);
        resource.allowOutput();
      }
    } catch (InterruptedException ex) {
    }
  }
}

class Producer implements Runnable {
  static String message[] = { "A", "B", "C", "D", "E", "F" };

  int id;

  Resource resource;

  public Producer(int id, Resource resource) {
    this.id = id;
    this.resource = resource;
  }

  public void run() {
    resource.displayOutput(id, message);
  }
}








7.8.Wait Notify
7.8.1.Wait and Notify
7.8.2.Block and wait
7.8.3.Both wait() and notify() must be called in synchronized code.
7.8.4.Using Wait() and Notify() to Control Access to a Shared Resource