Hi Readers Before getting in to the Producer Consumer Problem also know as bounder-buffer problem. which means producer is producing it and consumer is waiting for it,this continues to be wasting CPU Cycles.
Producer Consumer Problem is the classic example for this and we see through the below example
Consider Below four classes:
// GetSet, the queue that you’re trying to synchronize;
class GetSet {
int n;
boolean valueSet = false;
synchronized int get() {
System.out.println("Got: " + n);
return n;
}
synchronized void put(int n) {
this.n = n;
System.out.println("Put: " + n);
}
}
//Producer, the threaded object that is producing queue entries;
class Producer implements Runnable {
GetSet q;
Producer(GetSet q) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while(true) {
q.put(i++);
}
}
}
//Consumer, the threaded object that is consuming queue entries;
class Consumer implements Runnable {
GetSet q;
Consumer(GetSet q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
q.get();
}
}
}
//PC, the tiny class that creates the single GetSet,Producer, and Consumer.
class PC {
public static void main(String args[]) {
GetSet q = new GetSet();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}
Press Control-C to stop.
Put: 0
Put: 1
Put: 2
Put: 3
Put: 4
Got: 4
Got: 4
Got: 4
Got: 4
Got: 4
Got: 4
Got: 4
Got: 4
Got: 4
Got: 4
Got: 4
Got: 4
Got: 4
Got: 4
Got: 4
Got: 4
Got: 4
Got: 4
As you can see, after the producer put 1, the consumer started and got the same 1 five
times in a row. Then, the producer resumed and produced 2 through 7 without letting
the consumer have a chance to consume them.
The Solution to avoid this pooling Java includes an elegant inter process communication mechanism via
the wait( ), notify( ), and notifyAll( ) methods.
Please see the following snippet
class GetSet {
int n;
Boolean visited=Boolean.FALSE;
synchronized int get() {
if(!visited) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Got: " + n);
notify();
visited=Boolean.FALSE;
return n;
}
synchronized void put(int n) {
if(visited) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.n = n;
visited=Boolean.TRUE;
notify();
System.out.println("Put: " + n);
}
}
Here We are Producing and consuming in the above way, When using the above way Producer will be Suspended until the Producer notifies it is able to produce, and consumer can consume it.some output from this program, Hence wasting the CPU Cycles .
which shows the clean synchronous behavior:
Press Control-C to stop.
Put: 0
Got: 0
Put: 1
Got: 1
Hope Producer Consumer Problem is solved . Happy Reading !!!
No comments:
Write comments