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

Home
SCJP
1.Java Source And Data Type
2.Operators
3.Modifiers
4.Type Casting
5.Statements
6.Object Oriented
7.Thread
8.Utility Classes
9.File
SCJP » Thread » Wait Notify 
7.8.4.Using Wait() and Notify() to Control Access to a Shared Resource
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[inew 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
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.