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

3 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. I was a girl, but clumsy things. I do not know how to cook, sew, above, ca. I have too insipid and tedious, but that's my personality. It's hard to change
    baixar facebook l baixar facebook l baixar whatsapp l baixar whatsapp

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...