Sunday, December 30, 2012
Producer Consumer Problem with Wait and Notify Example
Producer Consumer Problem is a classical concurrency problem and in fact it is one of the concurrency design pattern. In last article we have seen solving Producer Consumer problem in Java using blocking Queue but one of my reader emailed me and requested code example and explanation of solving Producer Consumer problem in Java with wait and notify method as well, Since its often asked as one of the top coding question in Java. In this Java tutorial, I have put the code example of wait notify version of earlier producer consumer concurrency design pattern. You can see this is much longer code with explicit handling blocking conditions like when shared queue is full and when queue is empty. Since we have replaced BlockingQueue with Vector we need to implement blocking using wait and notify and that's why we have introduced produce(int i) and consume() method. If you see I have kept consumer thread little slow by allowing it to sleep for 50 Milli second to give an opportunity to producer to fill the queue, which helps to understand that Producer thread is also waiting when Queue is full.
Here is complete Java program to solve producer consumer problem in Java programming language. In this program we have used wait and notify method from java.lang.Object class instead of using BlockingQueue for flow control.
That’s all on How to solve producer consumer problem in Java using wait and notify method. I still think that using BlockingQueue to implement producer consumer design pattern is much better because of its simplicity and concise code. At the same time this problem is an excellent exercise to understand concept of wait and notify method in Java.
Other Java concurrency Interview Questions you may like