Producer and Consumer Java Multi-threading code

The following code is used for demonstrating thread-safety issues on eclipse.

Step 1: ProducerConsumerTest

Step 2: Producer thread.

Step 3: Consumer thread.

Step 4: ProducerConsumer logic.

Key Points

1) The wait & notifyAll methods in the java.lang.Object class is used for inter-thread communication to wait for the object’s lock or to tell other waiting threads that the lock has been relinquished.

2) The wait & notifyAll methods must be invoked within a synchronized method or block.

3) The “ProducerThread” and “ConsumerThread” are invoked by the JVM main thread, and they run for ever until the program is killed as they are run within ” while (true)“.

4) ArrayBlockingQueue is a “FIFO” (i.e. First In First Out) data structure, which is typically used to have on thread produce objects, which another thread consumes.

5) When the blocking queue reaches its upper limit, the producing thread is blocked while trying to insert the new object. It remains blocked until a consuming thread takes an object out of the queue. The consume thread gets blocked when the queue is empty. The “ConsumerThread” waits for the “ProducerThread” to insert an object into queue and the notify all the blocked threads.

800+ Java Interview Q&As Menu