Professional Documents
Culture Documents
Producer Consumer Problem
Producer Consumer Problem
Introduction
Producer Consumer design pattern has two threads namely: the Producer and the
Consumer. These threads are linked by a common buffer which is basically a queue.
Both the threads are independent in their nature of work. The producer will generate the
data, put it in the queue and keep on repeating the same process. The consumer will keep
on consuming or using the data by removing it from the queue.
Solution:
The BlockingQueue interface provides two methods put() and take() which are used
implicitly in blocking the Producer and the Consumer thread respectively. The thread
(Consumer) trying to remove item from an empty queue waits or is blocked until the
Producer thread adds an item to the queue. Similarly, the thread (Producer) trying to add an
item to a full queue is blocked until any Consumer thread makes some space in the queue
by removing the item(s) from the queue.
The code snippet given below represents a typical Producer class generating some data and
2
putting it in the BlockingQueue. If the buffer is full, it will wait for the Consumer thread to
remove some data from the queue before resuming its operation again. We are trying to
generate some Integer value as the data here in this example.
package com.javahungry;
import java.util.concurrent.BlockingQueue;
Consumer Class
The code snippet given below represents a Consumer class that removes the data from
queue and does some processing on it. If the buffer is empty, it will wait until the Producer
thread generates and puts some data into the queue.
package com.javahungry;
import java.util.concurrent.BlockingQueue;
package com.javahungry;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
Output:
Data produced : 10
Data produced : 20
Data consumed : 10
Data produced : 30
Data consumed : 20
Data produced : 40
Data consumed : 30
Data produced : 50
Data consumed : 40
Data consumed : 50
Data produced : 60
Data produced : 70
Data consumed : 60
Data produced : 80
Data consumed : 70
Data produced : 90
Data produced : 100
Data consumed : 80
Data consumed : 90
Data consumed : 100
It is evident from the above output that the data is getting generated and consumed
smoothly in a First-In, First-Out order as it is the feature of LinkedBlockingQueue. The
Producer thread is creating the data, putting it in the queue and Consumer thread is
removing it from the data implicitly without any need to write and notify statements. This
wraps up this article on Producer Consumer Problem in Java using multithreading
(BlockingQueue).