Producer Consumer Problem in Java

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

In the producer–consumer problem there are two processes, first is the producer and the second is the 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 to consume the data, one piece at a time, and remove it from the buffer.

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

Constructors in Java- Type Overloading and examples

Static keyword in Java with uses and Examples

Exception Handling in Java: Hierarchy Example and Types

User Defined exception in Java | Java custom exception with examples

Solution of Producer Consumer Problem in Java

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 the consumer process. The 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 the buffer by the producer process it also notifies the Consumer, to starts consume the data from the 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 the producer class.      

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

In the above java program, we can see that the production process produces the data and is consumed by the consumer process, then again a producer process produces new data and is consumed by the consumer process, and so on.                       

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

Above is the Producer Consumer Problem in Java.