The producer-consumer problem is one of the most frequently encountered problems when we attempt multi threaded programming.First of all, let us see the characteristics of the producer-consumer problem:
- Producer produce items.
- Consumer consume the items produced by the producer.
- Producer finish production and let the consumers know that they are done.
package rakesh;
public class Producer_Consumer
{
public static void main(String args[])
{
Methods m1=new Methods();
Producer p1=new Producer(m1,1);
Consumer c1=new Consumer(m1,1);
p1.start();
c1.start();
}
}
class Methods
{
private int content;
boolean available=false;
public synchronized int get()
{
while(available==false)
{
try
{
wait();
}
catch(Exception e)
{
System.out.println(e);
}
}
available=false;
notifyAll();
return content;
}
public synchronized void put(int value)
{
while(available==true)
{
try
{
wait();
}
catch(Exception e)
{
System.out.println(e);
}
}
available=true;
content=value;
notifyAll();
}
}
class Producer extends Thread
{
Methods method;
int number;
Producer(Methods method,int num)
{
this.method=method;
number=num;
}
public void run()
{
for(int i=0;i<10;i++)
{
method.put(i);
System.out.println("Producer #"+this.number+":"+i);
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
}
}
class Consumer extends Thread
{
Methods method;
int number;
Consumer(Methods method,int num)
{
this.method=method;
number=num;
}
public void run()
{
for(int i=0;i<10;i++)
{
int value=method.get();
System.out.println("Consumer #"+this.number+":"+value);
}
}
}