Friday, April 21, 2017

How to Solve Producer Consumer Problem in Java

Producer Consumer Problem is an important design concept involving multi-threading and inter thread communication. The main concept is that,Producer thread will produce the items to the Queue Consumer thread will Consume items from the Queue.If the Queue is empty Consumer thread has to call wait() method on the Queue object then it will enter into waiting state.After producing the items Producer thread has to give notification so that Consumer thread will get that notification and consume items.

Pseudo code to solve produce consumer problem:


Example:
This program shows how to solve producer consumer problem using wait() and notify()

class InterThread
{
public static void main(String args[])throws Exception
{
//producer produces some data which consumer consumes
Producer p1=new Producer();
//pass producer object to consumer so that it is then available to consumer
Consumer c=new Consumer(p1);
//create two threads and attach producer and consumer
Thread t1=new Thread(p1);
Thread t2=new Thread(c);
//Run the threads
t2.start();//consumer waits
t1.start();//producer starts production
}
}
class Producer extends Thread
{
//to add data,we use string buffer object
StringBuffer sb;
Producer()
{
sb=new StringBuffer();//allot memory
}
public void run()
{
synchronized(sb)
{
//go on appending data to string buffer
for(int i=1;i<=10;i++)
{
try{
sb.append(i+":");
Thread.sleep(2000);
System.out.println("adding");
}
catch(Exception e)
{}
}
//data production is over,so notify to consumer thread
sb.notify();
}
}
}
class Consumer extends Thread
{
//creates producer refercence to refer to producer object from consumer class
Producer prod;
Consumer(Producer prod)
{
this.prod=prod;
}
public void run()
{
synchronized(prod.sb)
{
//wait till a notification is received from producer thread
try{
prod.sb.wait();
}
catch(Exception e)
{}
//when data production is over,display data of string buffer
System.out.println(prod.sb);
}
}
}

Output:
adding
adding
adding
adding
adding
adding
adding
adding
adding
adding
1:2:3:4:5:6:7:8:9:10:

Read Also:

InterThread Communication
Synchronization Interview Questions
How to find duplicate elements in array



No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...