Overview
For multi -threaded programs, producers and consumer models are very classic models. More accurate, it should be called "producer-consumer-warehouse model". After leaving the warehouse, producers and consumers lack the shared storage space, and there is no problem that is not collaborative.
Exemplary example
Define a scene. A warehouse only allows 10 items to be stored. Producers can put a product at each time, and consumers can take out a product from it at a time. At the same time, you need to pay attention to the following 4 points:
1. Only one producer can be produced in the same time. The production method needs to lock the synchronized.
2. Only one consumer consumption can be available in the same time. The consumption method needs to lock the synchronized.
3. When the warehouse is empty, consumers cannot continue to consume. Consumers need to recycling whether the current warehouse status is empty before consumer consumption. If empty, the consumer thread requires WAIT, and the release lock allows other synchronization methods to execute.
4. When the warehouse is full, the producer cannot continue to produce. The producer's production money needs to be determined whether the current warehouse status is full. If full, the production thread needs to be wait, and the release lock allows other synchronization methods to execute.
The example code is as follows:
Public Class Concurrence {Public Static Void Main (String [] ARGS) {Warehouse Warehouse = New Warehouse (); Producer PRODUCER = New PRODUCER (Warehouse) ; Consumer Consumer = New Consumer (Warehouse); New Thread (Producer) .start () ; New Thread (Consumer) .start ();}} Class Warehouse {Private Static Final Int Store_size = 10; Private String [] StoreProduts = New String [Store_size] ; Private int int index = 0; Public void pushproduct (String Product) { Synchronized (this) {While (Index == Store_size) {try {this.wait ();} Catch (interruptedException E) {e.printstacktrace ();}} ts [Index ++] = Product; this.notify (); System .out.println ("Production:" + Product + ", currently in the warehouse:" + Index + "a cargo"); == 0 ) {Try {this.wait ();} Catch (interruptedException E) {e.printstacktrace ();} string proput = StoreProduts [Index- 1]; .out.println ("Consumption:" + Product + ", the current warehouse:" + Index + "a cargo"); this.Notify (); Return Product;}} Class Producer Implements runnable {Warehouse Warehouse; LIC PRODUCER (Warehouse Wh) {this.Warehouse = whomride public void run () {for (int i = 0; i <40; i ++) {string product = "product"+i; this.warehouse.pushProduct (product); }} Class Consumer Implements Runnable {Warehouse Warehouse; Public Consumer (Warehouse Wh) {this.Warehouse = wh; {this.warehouse.getproduct ();} }}