In this blog, producer/consumer problem will be discussed. The contents include:
- Producer/Consumer Model
 - Producer/Consumer implementation
 
Producer/Consumer Model
The producer/consumer problem is a very typical multi-threaded problem. The objects involved include producer, consumer, warehouse and product. The relationship between them is as follows:
- The 
produceronly produces when thewarehouseis not full, and stops production when thewarehouseis full. Consumerscan only consume when there is aproductin thewarehouse, and wait when thewarehouseis empty.- When the 
consumerfinds that there is noproductin thewarehousefor consumption, he will notify theproducerto produce it. - When producing consumable 
products,producersshould notifyconsumerswho are waiting to consume. 
Producer/Consumer implementation
Let’s look at how to implement it using wait() and notify()
1  | public class Warehouse {  | 
1  | public class Producer {  | 
1  | public class Consumer {  | 
1  | public class Main {  | 
Results:
1  | Thread-0 produce( 60) --> left= 0, numberToBeProduced= 60, size= 60  | 
Produceris aproducerclass, which is associated with awarehouse. When theproducer()method of theproduceris called, it will create a new thread and produce the product in thewarehouse.Consumeris aconsumerclass, which is associated with awarehouse. When theconsume()method of theconsumeris called, it will create a new thread and consume the products in thewarehouse.Warehouseis awarehouseclass, which recordscapacityof the warehouse andcurrent numberof products in the warehouse.
The produce() and consume() methods of the warehouse are both synchronized methods. Entering the synchronized method means that this thread has acquired the synchronization lock of the warehouse object. This means that only one producer and consumer thread can run at a time.
For the production method produce(): when the warehouse is full, the producer thread waits, and it needs to wait for the consumer to consume the product before the producer thread can produce. After the producer thread produces the product, it will wake up all threads wait on the synchronized lock through notifyAll(), including consumer threads, which we call notify consumers to consume.
For the consumption method consume(): when the warehouse is empty, the consumer thread waits and needs to wait for the producer to produce the product before the consumer thread can consume. After the consumer thread consumes the product, it will wake up all threads the synchronization lock through notifyAll(), including producer threads, which we call notify producers to produce.