Two implementations of producer consumer model for Java Multithreading Concurrency series

Source: Internet
Author: User

Using producer and consumer patterns in concurrent programming can solve most concurrency problems. This mode improves the overall processing speed of the program by balancing the productivity of the production line and the consuming thread.

Why use 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. in order to solve the problem of unbalanced production and consumption capacity, we have a model of producer and consumer.

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.

This blocking queue is used to decouple producers and consumers. Throughout most design patterns, a third party is found to decouple, such as the factory model of the third party is the factory class, template mode of the third party is a template class. In the process of learning some design patterns, if we first find the third party of this pattern, we can quickly familiarize ourselves with a design pattern.

The production/consumer model is described as follows:one or more producers produce some type of data and place buffers (which can be arrays or data structures such as queues);One consumer can fetch data from the buffer and fetch one item at a time;The system is guaranteed to avoid duplication of buffers, meaning that only one principal (producer or consumer) can access the buffer at any time. the problem is to ensure that the buffer does not overflow, that is, when the buffer is full, the generator does not continue to add data to it, and when the buffer is empty, the consumer does not remove the data from it. The producer-consumer model is a classic design pattern in concurrent, multithreaded programming, where producers and consumers decouple through decoupled execution, simplifying the development model where producers and consumers can produce and consume data at different speeds.  

Producer-consumer patterns in the real world

Producer and consumer models are ubiquitous in life and describe the relationship between coordination and collaboration. For example, a person is preparing food (producers), while another person is eating (a consumer), they use a common table for placing plates and taking dishes, producers prepare food, and if the table is full, wait for the consumer (that food) to wait if the table is empty. The table here is a shared object.

Producer and consumer models, to ensure that the following points: 1 at the same time only one producer can produce 2 at the same time only one consumer consumes 3 producer production while the consumer cannot consume 4 consumer consumption while the producer cannot produce 5 shared space when the consumer cannot continue to consume 6 Producers cannot continue production when space is full
  let's look at an example like this:producer: Put Apples in a public boxconsumer: Take apples from a public boxBox: The capacity of the box cannot exceed 5   Here we use the two methods to implement such a scenario separately. method One: Wait () and notify () communication method implementation 
 Packageproducer consumers;/**producer and consumer models, to ensure that: * 1 only one producer can produce at the same time * 2 at the same time only one consumer consumption * 3 producer production While the consumer cannot consume * 4 consumer consumption while the producer can not produce * 5 shared space when the consumer cannot continue Consumption * 6 The producer cannot continue production when the space is full * **/ Public classPublicbox {Private intApple = 0;  Public synchronized voidIncreace () { while(Apple = = 5) {             Try{wait (); } Catch(interruptedexception e) {e.printstacktrace (); }} Apple++; System.out.println ("Produced one.");     Notify (); }            Public synchronized voidDecreace () { while(Apple ==0) {             Try{wait (); } Catch(interruptedexception e) {e.printstacktrace (); }} Apple--; System.out.println ("A consumption of one");     Notify (); }         Public Static voidMain (String []args) {publicbox box=NewPublicbox (); Consumer Con=NewConsumer (box); Producer Pro=NewProducer (box); Thread T1=NewThread (con); Thread T2=NewThread (PRO);              T1.start ();                  T2.start (); }}//producer code (defined 10 times):classProducerImplementsRunnable {Privatepublicbox Box;  PublicProducer (publicbox box) { This. Box =box; } @Override Public voidrun () { for(inti=0;i<10;i++) {box.increace (); }     } }//Consumer code (same 10 times):classConsumerImplementsRunnable {Privatepublicbox Box;  PublicConsumer (publicbox box) { This. Box =box; } @Override Public voidrun () { for(inti=0;i<10;i++) {box.decreace (); }     } }

 The output is as follows: 

Has produced a
Has produced a
Has produced a
Has produced a
Consumption of a
Consumption of a
Consumption of a
Consumption of a
Has produced a
Has produced a
Has produced a
Has produced a
Has produced a
Consumption of a
Consumption of a
Consumption of a
Consumption of a
Consumption of a
Has produced a
Consumption of a

   method Two: Using blocking queue to implement producer consumer model 

The blocking queue implementation of the producer consumer model is super simple, it provides out-of-the-box support blocking method put () and take (), developers do not need to write confused wait-nofity code to achieve communication. Blockingqueue an interface, JAVA5 provides different realities, such as Arrayblockingqueue and Linkedblockingqueue, both of which are in FIFO order. And Arraylinkedqueue is a natural bounded, linkedblockingqueue selectable boundary. Here is an example of a complete producer consumer code that is easier to understand than the traditional wait, nofity code.

 
 Packageproducer Consumer 2;ImportJava.util.concurrent.BlockingQueue;ImportJava.util.concurrent.LinkedBlockingQueue; Public classPublicboxqueue { Public Static voidMain (String []args) {//defines a box with a size of 5Blockingqueue publicboxqueue=NewLinkedblockingqueue (5); Thread Pro=NewThread (NewProducer (publicboxqueue)); Thread Con=NewThread (NewConsumer (publicboxqueue));              Pro.start ();       Con.start (); }       }//producersclassProducerImplementsRunnable {Private FinalBlockingqueue Proqueue;  PublicProducer (Blockingqueue proqueue) { This. Proqueue =Proqueue; } @Override Public voidrun () {//TODO auto-generated Method Stub                for(inti=0;i<10;i++)              {                      Try{System. println ("The Apple number produced by the producer is:" + (i+1));//put ten apples on the number 1 toproqueue. Put (i+1); //Thread.Sleep (+);}Catch(interruptedexception e) {//Todo:handle ExceptionE.printstacktrace (); }                              }            }          }//ConsumerclassConsumerImplementsRunnable {Private FinalBlockingqueue Conqueue;  PublicConsumer (Blockingqueue conqueue) { This. Conqueue =Conqueue; } @Override Public voidrun () {//TODO auto-generated Method Stub                for(inti=0;i<10;i++)              {                      Try{System. println ("The Apple number for consumer consumption is:" +Conqueue. Take ()); //Thread. Sleep (3000); //sleep here is to see more clearly                                                } Catch(interruptedexception e) {//Todo:handle ExceptionE.printstacktrace (); }              }       }              }

 The results are as follows: 

Producer-produced Apple number: 1
Producer-produced Apple number: 2
Producer-produced Apple number: 3
consumer consumption of the Apple number is: 1
consumer consumption of the Apple number is: 2
consumer consumption of the Apple number is: 3
Producer-produced Apple number: 4
Producer-produced Apple number: 5
consumer consumption of the Apple number is: 4
consumer consumption of the Apple number is: 5
Producer-produced Apple number: 6
Producer-produced Apple number: 7
Producer-produced Apple number: 8
Producer-produced Apple number: 9
the number of apples produced by the producer is: Ten
consumer consumption of the Apple number is: 6
consumer consumption of the Apple number is: 7
consumer consumption of the Apple number is: 8
consumer consumption of the Apple number is: 9
consumer consumption of the Apple number is: Ten

The benefits of the producer consumer model

It is indeed a practical design pattern, often used to write multithreaded or concurrent code. Here are some of its advantages:

    1. It simplifies development, you can write the consumer and producer independently or concurrently, it just needs to know who the shared object is
    2. Producers don't need to know who the consumer is or how many consumers it is, and it's the same for consumers.
    3. Producers and consumers can perform at different speeds
    4. Separated consumers and producers are functionally capable of writing more concise, readable, maintainable code

Two implementations of producer consumer model for Java Multithreading Concurrency series

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.