Producer creates data and make it into a buffer. A consumer who always take the data from the buffer.
Let us consider a textile manufacturer. He/she is the
producer. Customer is the consumer.
Problem:
When the producer creates more products or no products.
When a consumer doesn’t take the product.
So the solution is implemented in java as Blocking Queue.
This queue provides the solution for this problem.
It is available in java.util.concurrent package.
Let us create the code.
Java implementation:
// Import the built in package
import java.util.concurrent.*;
//class producer declaration and function ‘run()’ defintion
class PCP_Producer implements Runnable {
private
BlockingQueue<Integer> queue1;
public
PCP_Producer(BlockingQueue<Integer> q) {
this.queue1 =
q;
}
@Override
public void run()
{
int i = 0;
try {
while
(true) {
System.out.println("The Produced data is " + i);
queue1.put(i++);
Thread.sleep(500); // let us make some time to simulate production
}
} catch
(InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
//Class Consumer declaration and method ‘run()’ definition.
class PCP_Consumer implements Runnable {
private
BlockingQueue<Integer> queue1;
public
PCP_Consumer(BlockingQueue<Integer> q) {
this.queue1 =
q;
}
@Override
public void run()
{
try {
while
(true) {
Integer item = queue1.take();
System.out.println("The Consumed data is: " + item);
Thread.sleep(1000); // make the time to Simulate the consumption
}
} catch
(InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
//main class. Object creation and function call.
public class PCP_Example {
public static void
main(String[] args) {
BlockingQueue<Integer> queue1 = new ArrayBlockingQueue<>(5);
Thread
pcp_producer = new Thread(new PCP_Producer(queue1));
Thread
pcp_consumer = new Thread(new PCP_Consumer(queue1));
pcp_producer.start();
pcp_consumer.start();
}
}
Output:
Compile and run the program to get the output.
C:\raji\blog>javac PCP_Example.java
C:\raji\blog>java PCP_Example
Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
Produced: 3
Produced: 4
Consumed: 3
Produced: 5
Consumed: 4
Consumed: 5
Here, the sample implementation of Producer consumer Problem
using Blocking Queue is done. Hope, this code will help you. Keep Coding!!!