First, what is the producer consumer model?
The producer-consumer model solves the problem of strong coupling between producers and consumers through a container. Producers and consumers do not communicate with each other directly, and through the blocking queue to communicate, so producers do not have to wait for consumer processing after the production of data, directly to the blocking queue, consumers do not find producers to data, but directly from the blocking queue, the blocking queue is equivalent to a buffer, Balance the processing power of producers and consumers.
Ii. why the use of producer and consumer models
In the world of threads, the producer is the thread of production data, and the consumer is the thread of consumption data. In multithreaded development, producers have to wait for the consumer to continue producing data if the producer is processing fast and the consumer processing is slow. Similarly, consumers must wait for producers if their processing power is greater than that of producers. To solve this problem, the producer and consumer models were introduced.
Third, the code implementation:
public class Product {public int id;public product (int ID) {super (); id = ID;} @Overridepublic String toString () {return ' id= ' + ID;}}
public class Factory {product[] products = new Product[10];int index = 0;public synchronized void push (Product p) {while ( index = = products.length) {try {this.wait ();} catch (Interruptedexception e) {e.printstacktrace ()}} This.notify ();p roducts[index] = p;index++;} Public synchronized Product POPs () {while (index = = 0) {try {this.wait ();} catch (Interruptedexception e) {E.printstacktrac E ();}} This.notify (); Index--;return products[index];}}
public class Producer implements Runnable {Factory Factory = null;public Producer (Factory Factory) {super (); this.factory = Factory;} @Overridepublic void Run () {for (int i = 0; i < i++) {Product p = new product (i); Factory.push (P); System.out.println (Thread.CurrentThread (). GetName () + "produced:" + p.tostring ()); try {thread.sleep ()} catch ( Interruptedexception e) {e.printstacktrace ();}}}}
public class Consumer implements Runnable {Factory Factory = null;public Consumer (Factory Factory) {super (); this.factory = Factory;} @Overridepublic void Run () {for (int i = 0; i < i++) {Product p = factory.pop (); System.out.println (Thread.CurrentThread (). GetName () + "consumed:" + p.tostring ()); try {thread.sleep ()} catch ( Interruptedexception e) {e.printstacktrace ();}}}}
public class Test {public static void main (string[] args) {Factory Factory = new Factory (); Producer P1 = new Producer (factory); Consumer P2 = new Consumer (factory); new Thread (p1). Start (); new Thread (P2). Start ();}
Java multi-thread producer consumer model