Interthread Communication

In this chapter you will learn:

  1. Solve the producer and consumer problem

producer and consumer problem

Java includes an interprocess communication mechanism via the wait(), notify(), and notifyAll() methods. These methods are implemented as final methods in Object, so all classes have them. All three methods can be called only from within a synchronized context.

  • wait() tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify().
  • notify() wakes up a thread that called wait() on the same object.
  • notifyAll() wakes up all the threads that called wait() on the same object. One of the threads will be granted access.

These methods are declared within Object, as shown here:

final void wait() throws InterruptedException 
final void notify() 
final void notifyAll()

The proper way to write this program in Java is to use wait() and notify() to signal in both directions:

The following code shows a solution for producer consumer problem. Suppose there is a box shared by both producers and consumers. The producers will produce if the box is empty or wait if the box is alreay full. The consumer will consume what is in the box or wait if the box is empty.

class SharedBox {
  int n;/*  j a v a 2s.  c  o m*/
  boolean valueSet = false;

  synchronized int get() {
    while (!valueSet)
      try {
        wait();
      } catch (Exception e) {
      }
    System.out.println("Got: " + n);
    valueSet = false;
    notify();
    return n;
  }
  synchronized void put(int n) {
    while (valueSet)
      try {
        wait();
      } catch (Exception e) {
      }
    this.n = n;
    valueSet = true;
    System.out.println("Put: " + n);
    notify();
  }
}

class Producer implements Runnable {
  SharedBox box;

  Producer(SharedBox q) {
    this.box = q;
    new Thread(this, "Producer").start();
  }

  public void run() {
    int i = 0;
    while (true) {
      box.put(i++);
    }
  }
}

class Consumer implements Runnable {
  SharedBox box;

  Consumer(SharedBox q) {
    this.box = q;
    new Thread(this, "Consumer").start();
  }

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

public class Main {
  public static void main(String args[]) throws Exception {
    SharedBox q = new SharedBox();
    new Producer(q);
    new Consumer(q);
    
    Thread.sleep(2000);
    System.exit(0);
  }
}

Next chapter...

What you will learn in the next chapter:

  1. How to use boolean variable to stop a thread
Home » Java Tutorial » Thread
Thread introduction
Thread Name
Thread Main
Thread sleep
Thread Creation
Thread join and is alive
Thread priorities
Thread Synchronization
Interthread Communication
Thread Step
Thread suspend, resume, and stop
ThreadGroup
BlockingQueue
Semaphore
ReentrantLock
Executor
ScheduledThreadPoolExecutor