Java Thread interthread communication for producer and consumer

Introduction

We can use the methods declared within Object to do interthread communication:

final void wait() throws InterruptedException  
final void notify()  
final void notify All() 
class Queue {
  int n;/*from w  ww .j  a v a 2  s .  c  o m*/
  boolean valueSet = false;

  synchronized int get() {
    while(!valueSet)
      try {
        wait();

      } catch(InterruptedException e) {
        System.out.println("InterruptedException caught");
      }

      System.out.println("Got: " + n);
      valueSet = false;
      notify();
      return n;
  }

  synchronized void put(int n) {
    while(valueSet)
      try {
        wait();
      } catch(InterruptedException e) {
        System.out.println("InterruptedException caught");
      }

      this.n = n;
      valueSet = true;
      System.out.println("Put: " + n);
      notify();
  }
}

class Producer implements Runnable {
  Queue queue;

  Producer(Queue q) {
    this.queue = q;
    new Thread(this, "Producer").start();
  }

  public void run() {
    int i = 0;

    while(true) {
      queue.put(i++);
    }
  }
}

class Consumer implements Runnable {
  Queue queue;

  Consumer(Queue q) {
    this.queue = q;
    new Thread(this, "Consumer").start();
  }

  public void run() {
    while(true) {
      queue.get();
    }
  }
}

public class Main {
  public static void main(String args[]) {
    Queue q = new Queue();
    new Producer(q);
    new Consumer(q);

    System.out.println("Press Control-C to stop.");
  }
}



PreviousNext

Related