Producer - Consumer Problem in Java

What is Producer - Consumer Problem?
In Simple term we can say, when two Process trying to access same(commonly shared) resource at the same time and one failed to do its operation because another process is using that resource.

In this article we'll generate the Producer - Consumer problem using threads that are trying to access common resource. One thread that is adding/removing records to the List<Integer> and another thread trying to print the records of List<Integer> one-by-one.

When you run the above program it'll throw an exception java.util.ConcurrentModificationException as shown in following output.

Note: When you execute this program in your system you won't get same output. It depends upon the execution of Thread in your system.

Output
As you can see clearly portion marked within =. Consumer Thread Iterating the List<Integer> and printed 0 and at the same time Producer Thread added record and Consumer Thread thrown an exception.

We can solve this problem using synchronized keyword. synchronized takes care for accessing List<Integer>, while one thread is accessing the List<Integer> another thread has to wait until first thread finishes its work.

Source Code(Solving Problem)
Following program will not give java.util.ConcurrentModificationException exception.