Producer Consumer Solution using wait(), notify() in Java
Learn how to write Java concurrency code for producer consumer pattern using wait and notify
The Producer-Consumer Problem is a classical concurrency problem and in fact, it is one of the most powerful concurrency design patterns which is used in most multithreaded Java applications.
In the last post, I have shown you how to solve the Producer-Consumer problem in Java using blocking Queue but one of my readers emailed me and requested a code example and explanation of solving the Producer-Consumer problem in Java with the wait and notify method as well .
Since it's often asked as one of the top coding questions in Java. In this post, I have put the code example of the wait notify version of the earlier producer-consumer concurrency design pattern.
You can see this is a much longer code with explicit handling blocking conditions like when the shared queue is full and when the queue is empty which can be tricky for anyone.
Since we have replaced
BlockingQueue
withArrayList
we need to implement blocking using wait and notify and that's why we have introduced theproduce(int i)
andconsume()
method.
If you see I have kept the consumer thread a little slow by allowing it to sleep for 50 Milliseconds to give an opportunity to the producer to fill the queue, which helps to understand that the Producer thread is also waiting when Queue is full.
By the way, if you are new to multithreading in Java then I also suggest you join a course like Multithreading and Parallel Computing in Java from Udemy. It's a great course to learn the multithreading basics and become a better Java developer.
Solving Producer-Consumer Problem in Java
Here is a complete Java program to solve the classic producer-consumer problem in the Java programming language.
Keep reading with a 7-day free trial
Subscribe to Javarevisited Newsletter to keep reading this post and get 7 days of free access to the full post archives.