Tuesday, 29 August 2017

Core Java Program for the producer consumer problem

Java Program for the producer consumer problem using notify () & Wait () statement

Program

class Main {
   public static void main(String[] args) {
      Shared s = new Shared();
      Producer p1 = new Producer(s);
      Consumer c1 = new Consumer(s);
      p1.start();
      c1.start();
   }
}
class Shared {
   private int contents;
   private boolean available = false;
   public synchronized int get() {
      while (available == false) {
         try
                {  wait(); }
         catch (InterruptedException e) {}
      }
      available = false;
      notifyAll();
      return contents;   }
 

 public synchronized void put(int value) {
      while (available == true) {
         try
{wait();}
         catch (InterruptedException e) { }
      }
      contents = value;
      available = true;
      notifyAll();
   }
}
class Consumer extends Thread {
    Shared s;
   public Consumer(Shared s)
 {this.s = s;}
   public void run() {
      int value = 0;
         for (int i = 0; i < 5; i++) {
            value = s.get();
            System.out.println("Consumer # got: " + value);
}
}
}
class Producer extends Thread {
Shared s;
public Producer(Shared s)
{this.s= s;}
public void run() {
for (int i = 0; i < 5; i++) {
s.put(i);
System.out.println("Producer #put: " + i);
try { sleep(2000); }
catch (InterruptedException e) { }
}
}

}

Output

producer consumer problem core java

0 comments:

Post a Comment