Producer Consumer Design Pattern With Blocking Queue Example in Java PDF
Producer Consumer Design Pattern With Blocking Queue Example in Java PDF
Javarevisited
Blog about Java programming language, FIX Protocol, Tibco Rendezvous and related Java technology stack.
Queue in Java
Java
Best of Javarevisited
How Android works, Introduction for Java
Programmers
Difference between Java and Scala Programming
Top 5 Java Programming Books for Developers
Top 10 JDBC Best Practices for Java programmers
Tips and Best practices to avoid
NullPointerException in Java
10 Object Oriented Design Principles Java
Programmer Should Know
10 HotSpot JVM Options, Every Java Programmer
Should Know
Follow Us
Follow @javinpaul
6,045 followers
Javarevisited
Follow
+1
+ 37,023
LinkedBlockingQueue is optionally bounded. here is a complete code example of Producer Consumer pattern with
BlockingQueue. Compare it with classic wait notify code, its much simpler and easy to understand.
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ProducerConsumerPattern {
public static void main(String args[]){
//Creating shared object
BlockingQueue sharedQueue = new LinkedBlockingQueue();
//Creating Producer and Consumer Thread
Thread prodThread = new Thread(new Producer(sharedQueue));
http://javarevisited.blogspot.sg/2012/02/producer-consumer-design-pattern-with.html
1/7
9/23/2014
Javarevisited
Like
}
//Producer Class in java
class Producer implements Runnable {
Followers
private final BlockingQueue sharedQueue;
}
//Consumer Class in Java
class Consumer implements Runnable{
private final BlockingQueue sharedQueue;
public Consumer (BlockingQueue sharedQueue) {
this.sharedQueue = sharedQueue;
}
@Override
public void run() {
while(true){
try {
System.out.println("Consumed: "+ sharedQueue.take());
} catch (InterruptedException ex) {
Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Output:
Produced: 0
Produced: 1
Consumed: 0
Produced: 2
Consumed: 1
Produced: 3
Consumed: 2
Produced: 4
Consumed: 3
Produced: 5
Consumed: 4
Produced: 6
Consumed: 5
Produced: 7
Consumed: 6
Produced: 8
Consumed: 7
Produced: 9
Consumed: 8
Consumed: 9
You see Producer Thread
Subscribe by email:
Subscribe
By Javin Paul
Search
produced number and Consumer thread consumes it in FIFO order because blocking
Thats all on How to use Blocking Queue to solve Producer Consumer problem or example of Producer consumer
design pattern. I am sure its much better than wait notify example but be prepare with both if you are going for any Java
Interview as Interview may ask you both way.
http://javarevisited.blogspot.sg/2012/02/producer-consumer-design-pattern-with.html
2/7
9/23/2014
edge.canon.co.in/EOS1200D
Say EOS 1200D & save INR 12995* on Double Zoom Kit. Get Free* gifts
Why wait, notify and notifyAll is defined in Object Class and not on Thread class in Java
20 Things on Synchronization, Synchroinzed Block, Method, locking and Threadsafety in Java
How to Join Multiple Threads in Java - Thread Join Example
ReentrantLock Example in Java, Difference between synchronized vs ReentrantLock
8 comments :
2011 ( 145 )
Anonymous said...
2010 ( 33 )
Recently I got this question in interview with different scenario. How to resolve the producer and consumer
problem so that my CPU cycle can be used to 100%. For ex if producer is producing less and consumer is consuming
fast then your CPU cycle is getting wasted which is associated with cost. So what would be strategy to resolve this.
Any suggestion?
References
Hi Javin, ..gr8 article few things that I want to add in this is...
BlockingQueue Code Example
Here is an example of how to use a BlockingQueue. The example uses the ArrayBlockingQueue implementation of
the BlockingQueue interface.
MySQL
Linux
Eclipse
First, the BlockingQueueExample class which starts a Producer and a Consumer in separate threads. The Producer
inserts strings into a shared BlockingQueue, and the Consumer takes them out.
jQuery
http://javarevisited.blogspot.sg/2012/02/producer-consumer-design-pattern-with.html
3/7
9/23/2014
Thread.sleep(1000);
queue.put("3");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Here is the Consumer class. It just takes out the objects from the queue, and prints them to System.out.
public class Consumer implements Runnable{
protected BlockingQueue queue = null;
public Consumer(BlockingQueue queue) {
this.queue = queue;
}
public void run() {
try {
System.out.println(queue.take());
System.out.println(queue.take());
System.out.println(queue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
April 13, 2013 at 9:26 PM
yyc said...
The above example is good but too simple. Would you minding providing a example with multiple producers and
consumers and stopping the program once producers have done their jobs?
October 8, 2013 at 8:30 PM
Anonymous said...
I tried out following implementation of Producer-Consumer and it doesn't list out all the elements from the list.
Few of them are missing.
I wanted to have one producer & multiple consumers and have the consumers take data out of the list in round
robin fashion, but not working as expected. Would you be able to point me out the error in the code? Thanks.
public class ProdConController {
public static void main(String[] args) throws Exception {
List stringList = new ArrayList();
SignalObject signalObject = new SignalObject();
ProdWorker prodWorker = new ProdWorker(stringList, signalObject);
ConWorker conWorker1 = new ConWorker(stringList, signalObject, "worker1");
ConWorker conWorker2 = new ConWorker(stringList, signalObject, "worker2");
Thread prodThrd = new Thread(prodWorker);
Thread conThrd1 = new Thread(conWorker1);
Thread conThrd2 = new Thread(conWorker2);
prodThrd.start();
conThrd1.start();
conThrd2.start();
prodThrd.join();
conThrd1.join();
conThrd2.join();
}
}
public class SignalObject {
private boolean isDataAvailable = false;
public synchronized boolean isDataAvailable() {
return isDataAvailable;
}
public synchronized void setDataAvailable(boolean dataAvailable) {
isDataAvailable = dataAvailable;
}
}
public class ProdWorker implements Runnable {
private List stringList;
private SignalObject signalObject;
public ProdWorker(List stringList, SignalObject signalObject) {
this.stringList = stringList;
this.signalObject = signalObject;
}
@Override
public void run() {
http://javarevisited.blogspot.sg/2012/02/producer-consumer-design-pattern-with.html
4/7
9/23/2014
http://javarevisited.blogspot.sg/2012/02/producer-consumer-design-pattern-with.html
5/7
9/23/2014
int n;
static Semaphore semCons = new Semaphore(0);
static Semaphore semProd = new Semaphore(1);
void put(int n)
{
try {
semProd.acquire();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.n=n;
System.out.println("Put : " + n);
semCons.release();
}
void get()
{
try {
semCons.acquire();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Got : "+n);
semProd.release();
}
}
class Consumer implements Runnable
{
SharedResource sr;
public Consumer(SharedResource sr)
{
this.sr = sr;
new Thread(this, "Consumer").start();
}
@Override
public void run()
{
for(int i=0;i<10;i++)
{
sr.get();
}
}
}
class Producer implements Runnable
{
SharedResource sr;
public Producer(SharedResource sr)
{
this.sr= sr;
new Thread(this,"Producer").start();
}
@Override
public void run()
{
for(int i=0;i<10;i++)
{
sr.put(i);
}
}
}
public class ProducerConsumer {
public static void main(String[] args) {
SharedResource sr = new SharedResource();
new Consumer(sr);
new Producer(sr);
}
}
May 22, 2014 at 4:58 AM
Post a Comment
http://javarevisited.blogspot.sg/2012/02/producer-consumer-design-pattern-with.html
6/7
9/23/2014
Comment as:
Publish
Google Account
Preview
Newer Post
Home
Older Post
About Me
Privacy Policy
http://javarevisited.blogspot.sg/2012/02/producer-consumer-design-pattern-with.html
7/7