I have implemented Classical example of producer and consumer. Here producer will sleep for 10 seconds after producing value = 0
[will not go waiting for the state because of queue size is one which is less than 10 ]. And the consumer will consume value =0
and notify the producer will sleep for one second.
So My question is that why Notify by the consumer is not interrupting producer thread and print Producer Exception cached
.
The output of the following program is like:
Producer add value=0
Consumer consumes value=0
(wait for 10 seconds)
Producer add value=1
Consumer consumes value=1
(wait for 10 seconds)
Producer add value=2
Consumer consumes value=2
Classical Example of Producer and consumer.
public class ClassicalProducerConsumer{
public static void main(String[] args) {
Buffer buffer = new Buffer(3);
Thread producer = new Thread(new Runnable() {
@Override
public void run() {
try {
int value = 0;
while (true) {
buffer.add(value);
value++;
Thread.sleep(10000); // Make producer wait for 10 seconds.
}
}catch (Exception ex){
System.out.println("Producer Exception cached");
ex.printStackTrace();
}
}
});
Thread consumer = new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
int value = buffer.poll();
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Consumer Exception cached");
e.printStackTrace();
}
}
});
producer.start();
consumer.start();
}
}
class Buffer{
Queue<Integer> queue;
int size;
public Buffer(int size) {
this.size = size;
queue = new LinkedList<>();
}
public void add(int value) throws InterruptedException {
synchronized (this){
while (queue.size() >=size){
wait();
}
System.out.println("Producer add value="+ value);
queue.add(value);
notify();
}
}
public int poll() throws InterruptedException {
synchronized (this){
while (queue.size()==0){
wait();
}
int value = queue.poll();
System.out.println("Consumer consumes value="+ value);
notify();
return value;
}
}
}