Producer Consumer Problem in Java

In computing, producer–consumer problem also known as the bounded-buffer problem.

In the producer–consumer problem there are two processes, first is producer and the second is consumer, who share a common, fixed-size buffer.

 The producer’s job is to generate data, put it into the buffer and start again.

At the same time, the consumer’s job is consuming the data, one piece at a time and removing it from the buffer.

The producer–consumer problem occurs when the producer try to add data into the buffer if it’s full and the  same consumer  try to remove data from an empty buffer.

Solution of Producer & Consumer

The solution for the producer must go to sleep if the buffer is full and the consumer must consume data. 

Once the data is consumed it removes from the buffer by consumer process. Consumer process  also notifies the producer, to  starts fill the buffer again.

Similarly, the consumer process must go to sleep if it finds the buffer is empty and the producer puts data into the buffer.

Ones the data is filled into buffer by producer process it also notifies the Consumer, to  starts consume the data from buffer.

Description : In the above program there are four classes: Item, Producer, Consumer and  PCDemo

Item: the class is trying to synchronize.  

Producer: produces the data.   

Consumer: consumes the data produced by producer class.      

PCDemo: a class that creats the class Item, Producer and Consumer.

In the above program we can see that, producer process producess the data and  consumed by consuner process, then again a producer process producess a new data and consumed by consumer process and so on.                       

To stop the execution we have to pess ”Ctrl+C”.