Producer Consumer Problem - JAVA

//PRODUCER CONSUMER PROBLEM
class Buffer
{
private int data;
private boolean available=false;
public synchronized int get()
{
while(available==false)
{
try
{
wait();
}
catch ( InterruptedException e)
{}
}
available=false;
notifyAll();
return data;
}
public synchronized void put(int value )
{
while(available==true)
{
try
{
wait();
}
catch ( InterruptedException e)
{}
}
data=value;
available=true;
notifyAll();
}
}
class Producer extends Thread
{
private Buffer buf;
public Producer (Buffer c)
{
buf=c;
}
public void run()
{
for(int i=0;i<5;i++)
{
buf.put(i);
System.out.println("Producer produced item:"+i);
try
{
sleep( (int) (Math.random()*100));
}
catch (InterruptedException e) { }
}
}
}
class Consumer extends Thread
{
private Buffer buf;
public Consumer (Buffer c)
{
buf=c;
}
public void run()
{
int value=0;
for(int i=0;i<5;i++)
{
value=buf.get();
System.out.println("Consumer consumed item:"+value);
try
{
sleep( (int) (Math.random()*100));
}
catch (InterruptedException e) { }
}
}
}
public class prodcons
{
public static void main (String args[])
{
Buffer b=new Buffer();
Producer p=new Producer(b);
Consumer c=new Consumer(b);
p.start();
c.start();
}
}
OUTPUT
students@ccflab-desktop:~$ javac prodcons.java
students@ccflab-desktop:~$ java prodcons
Producer produced item:0
Consumer consumed item:0
Producer produced item:1
Consumer consumed item:1
Producer produced item:2
Consumer consumed item:2
Producer produced item:3
Consumer consumed item:3
Producer produced item:4                                      //http://2k8618.blogspot.com
Consumer consumed item:4
students@ccflab-desktop:~$

Download

8 comments:

  1. The simplest 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.

    ReplyDelete
  2. This article is really fantastic and thanks for sharing the valuable post

    overwatch shirts

    ReplyDelete
  3. I am looking for my memories through the stories, the narrative of people. I feel it is difficult but I will try.
    povaup

    ReplyDelete
  4. I have read your article, the information you give is very interesting.
    pocatravel
    I have read your article, the information you give is very interesting.
    pocatravel

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...