Experiment No. - 13: AIM - Write A Program To Implement Producer Consumer Problem in Java
Experiment No. - 13: AIM - Write A Program To Implement Producer Consumer Problem in Java
– 13
AIM – Write a Program to Implement Producer Consumer problem in Java
using Thread.
· The producer’s job is to generate data, put it into the buffer, and start again.
· At the same time, the consumer is consuming the data (i.e. removing it from
the buffer), one piece at a time.
Problem:
To make sure that the producer won’t try to add data into the buffer if it’s full
and that the consumer won’t try to remove data from an empty buffer.
Solution:
The producer is to either go to sleep or discard data if the buffer is full. The next
time the consumer removes an item from the buffer, it notifies the producer,
who starts to fill the buffer again. In the same way, the consumer can go to sleep
if it finds the buffer to be empty. The next time the producer puts data into the
buffer, it wakes up the sleeping consumer.
import java.util.Scanner;
class Q {
int n;
while(!signal)
try {
wait();
} catch(InterruptedException e)
{ System.out.println("InterruptedException
caught");
signal = false;
notify();
return n;
while(signal)
try {
} catch(InterruptedException e)
{ System.out.println("InterruptedException
caught");
this.n = n;
signal = true;
notify();
Q q;
int n;
Producer(Q q,int n) {
this.n=n;
this.q = q;
{ System.out.println("Producer thread
created"); int i = 0;
while(i<n)
{ q.produce(+
+i);
}
Q q;
int n;
Consumer(Q q,int n) {
this.q = q;
this.n=n;
{ System.out.println("Consumer thread
created"); while(true) {
q.consume();
int n;
Q q = new Q();
new Producer(q,n);
new Consumer(q,n);
}
OUTPUT –