Threading Model   «Prev 


Implementing the Consumer-Producer Model

The following program implements a simple consumer-producer model. A Producer thread produces letters of the alphabet and three Consumer threads consume these letters. A Resource object is shared by these four threads. This object provides synchronized access to the letters by means of its consumeIt() and produceIt() methods. These methods invoke the wait() and notifyAll() methods to support the consumer-producer model.

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

class Resource {
 char ch;
 boolean okToConsume = false;
 public synchronized void consumeIt(int id) {
   try {
     while (!okToConsume) {
       wait();
     } // end - while
     okToConsume = false;
     System.out.println("Consumer " + id + " consumes " + ch + ".");
   }
   catch (InterruptedException ex) {
   }  
 }

 public synchronized void produceIt(char ch) {
   this.ch = ch;
   System.out.println("Producer produces " +
     ch + ".");
   okToConsume = true;
   notifyAll();
 }
}

class Producer implements Runnable {
 Resource resource;
 public Producer(Resource resource) {
   this.resource = resource;
 }
 public void run() {
   char ch = 'A';
   try {
     while (true) {
       Thread.currentThread().sleep((long)1000);  
       resource.produceIt(ch);
       if (ch == 'Z')
         ch = 'A';
       else
         ch = (char)(ch + 1);
     }
   }
   catch (InterruptedException ex) {
   }
 }
}

class Consumer implements Runnable {
 int id;
 Resource resource;
 public Consumer(int id,Resource resource) {
   this.id = id;
   this.resource = resource;
 }
 public void run() {
   for (int i = 0; i < 10; i++) 
     resource.consumeIt(id);
 }
}