Saturday, June 23, 2012

Producer Consumer Problem - Java solution

Shared Stack and Signaling variables
final Stack stack = new Stack();
final int maxLimit = 5;
final Object obj1 = new Object();
final Object obj2 = new Object();
Producer code
Thread producer = new Thread() {

 @Override
 public void run() {

 while (true) {
  synchronized (obj1) {
   if (stack.size() == maxLimit) {
    try {
     obj1.wait();
    }

    catch (InterruptedException e) {
     e.printStackTrace();
    }
   }
  }
  synchronized (obj2) {
   stack.push("producing items....");
   obj2.notify();
  }
 }

 }
};

Consumer code
Thread consumer = new Thread() {

 @Override
 public void run() {

  while (true) {
   synchronized (obj2) {
    if (stack.size() == 0) {
     try {
      obj2.wait();
     }
     catch (InterruptedException e) {
      e.printStackTrace();
     }
    }
   }
   
   synchronized (obj1) {
    stack.pop();
    obj1.notify();
   }
  }
 }
};
Then start producer thread and consumer thread as follow.
producer.start();
consumer.start();
If this code is a buggy one please feel free to correct me.

1 comment:

  1. One of the best way to solve the producer consumer problem is by using Blocking-queue, as explained in this tutorial, but if you really want to understand the core concept behind producer consumer pattern i.e. inter-thread communication in Java, then you must solve this problem using wait and notify method in Java. when you solve it hard way, you learn more, that's true in any programming language.

    ReplyDelete