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
producer
only produces when thewarehouse
is not full, and stops production when thewarehouse
is full. Consumers
can only consume when there is aproduct
in thewarehouse
, and wait when thewarehouse
is empty.- When the
consumer
finds that there is noproduct
in thewarehouse
for consumption, he will notify theproducer
to produce it. - When producing consumable
products
,producers
should notifyconsumers
who 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 |
Producer
is aproducer
class, which is associated with awarehouse
. When theproducer()
method of theproducer
is called, it will create a new thread and produce the product in thewarehouse
.Consumer
is aconsumer
class, which is associated with awarehouse
. When theconsume()
method of theconsumer
is called, it will create a new thread and consume the products in thewarehouse
.Warehouse
is awarehouse
class, which recordscapacity
of the warehouse andcurrent number
of 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
.