Overview for multi-threaded routines, the producer and consumer models are very classic models. More precisely, it should be called "producer-consumer-warehouse model". Leaving the warehouse, producers and consumers lack shared storage space, and there is no problem of collaboration.
Example defines a scene. A warehouse is allowed to store only 10 items, and each time a producer can put a product into it, the consumer can take out one item at a time. At the same time, the following 4 points need to be noted: 1. Only one producer can be produced at the same time, and the production method needs to be locked synchronized. 2. At the same time there can only be one consumer consumption, the consumption method needs to lock synchronized. 3. When the warehouse is empty, consumers cannot continue to consume. Consumers need to cycle before consumption to determine whether the current warehouse state is empty, empty the consumer thread needs to wait, release the lock allows other synchronization methods to execute. 4. When the warehouse is full, the producer cannot continue to produce, the producer produces the money needs to cycle to determine whether the current warehouse status is full, then the production line needs to wait, release lock allows other synchronization methods to execute.
The sample 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[] storeproducts = new String[store_size];p rivate int index = 0;public void Pushproduct (String product) {synchronized (this) {while (index = = store_size) {try {this.wait (); } catch (Interruptedexception e) {e.printstacktrace ();}} storeproducts[index++] = product;this.notify (); System.out.println ("produced:" + Product + ", currently in the warehouse total:" + index+ ");}} Public synchronized String getproduct () {synchronized (this) {while (index = = 0) {try {this.wait ();} catch (Interruptedexc Eption e) {e.printstacktrace ();}} String Product = storeproducts[index-1];index--; System.out.println ("Consumption:" + Product + ", currently in the warehouse total:" + index+ "); This.notify (); return product;}} Class Producer ImplemenTS Runnable {WareHouse warehouse;public Producer (WareHouse wh) {this.warehouse = WH;} @Overridepublic void Run () {for (int i = 0; i < i++) {String Product = "Product" + i;this.warehouse.pushproduct (pro duct);}}} Class Consumer implements Runnable {WareHouse warehouse;public Consumer (WareHouse wh) {this.warehouse = WH;} @Overridepublic void Run () {for (int i = 0; i <; i++) {this.wareHouse.getProduct ();}}}
Java concurrent Collaboration--producer, consumer model