The Java Program: Consumer.java

  1 import java.util.Date;
  2 import java.util.LinkedList;
  3 
  4 class Producer implements Runnable {
  5 
  6    final private LinkedList messages = new LinkedList();
  7    final static int MAXQUEUE = 5;
  8  
  9    public void run() {
 10       try {
 11          while (true) {
 12             putMessage (new Date());
 13             Thread.sleep (1000);
 14          }
 15       } catch (InterruptedException e) {
 16          e.printStackTrace (System.err);
 17       }
 18    }
 19 
 20    private synchronized void putMessage (final Date d) throws InterruptedException {
 21       /*
 22         The producer and consumers are waiting for different conditions ("not full"
 23         and "not empty" respectively) though they are using the same lock/signal "this".
 24         Even so "this" thread is the unique producer thread and so it cannot now be
 25         waiting, so we can safely notify just some one consumer thread.
 26       */
 27       notify();
 28 
 29       // wait until a possible change in queue size
 30       while (messages.size()==MAXQUEUE) wait();
 31 
 32       messages.add (d.toString());
 33    }
 34 
 35    public synchronized String getMessage() throws InterruptedException {
 36       /*
 37         The producer and other consumers are waiting for different conditions
 38         on the same lock/signal "this".  To be safe we notify all.
 39       */
 40       notifyAll();
 41 
 42       // wait until a possible change in queue size
 43       while (messages.size()==0) wait();
 44 
 45       return (String) messages.removeFirst();
 46    }
 47 }
 48 
 49 public class Consumer implements Runnable {
 50 
 51    final Producer producer;  // References to the producer
 52         
 53    Consumer (Producer p) {
 54       producer = p;
 55    }
 56  
 57    public void run() {
 58       final String me = Thread.currentThread().getName();
 59       try {
 60          while (true) {
 61             final String message = producer.getMessage();
 62             System.out.println (me + " got message: " + message);
 63             Thread.sleep (2000);
 64          }
 65       } catch (InterruptedException e) {
 66          e.printStackTrace (System.err);
 67       }
 68    }
 69  
 70    public static void main(String args[]) {
 71       final Producer producer = new Producer();  // One unique producer
 72       final Thread p = new Thread (producer);
 73       p.start();
 74       new Thread (new Consumer (producer), "One").start();
 75       new Thread (new Consumer (producer), "Two").start();
 76       new Thread (new Consumer (producer), "Three").start();
 77    }
 78 }