An Implementation of the producer and consumption modes.

Source: Internet
Author: User

An Implementation of the producer and consumption modes.
1. Concept

In concurrent programming, the concept of producer and consumer patterns is often mentioned, which is often used to improve the efficiency of concurrent programming. The producer is the thread that generates data, and the consumer is the thread that consumes data. In multi-thread concurrent programming, it is very likely that when the production speed of the producer is inconsistent with the consumption speed of the consumer, if some measures are not taken, it is certain that unexpected consequences will be stored. Therefore, a blocking queue is often used to act as a buffer, and all the data produced by the producer is put down to block the queue, when consumers consume data, they also need to block the queue, which balances the data processing capabilities of producers and consumers.

2. Implementation

The key to solving the problem between producers and consumers is to use a blocking queue as the buffer, which must have two features: 1. when data is retrieved, if the queue is empty, the Data fetch thread must be blocked until the new data produced by the producer is put into the queue. 2. During data production, if the queue is found to be full, the producer must be blocked until the blocking queue has a blank space.
In Java,For LinkedBlockingQueueTake () andThe put () method exactly meets these two conditions and is thread-safe.
Take (): When the queue is empty, it will be blocked until a new element of the queue comes in.
Put (): When the queue is full, it will be blocked until the queue has a new vacancy.

Go directly to the Code:

Public class ProducerAndConsumer {static BlockingQueue  FruitsBuffer = new LinkedBlockingQueue <> (); public static void main (String [] args) {Thread p1 = new Thread (new Producer (fruitsBuffer), "producer 1 "); thread c1 = new Thread (new Consumer (fruitsBuffer), "consumer 1"); Thread c2 = new Thread (new Consumer (fruitsBuffer), "consumer 2 "); thread c3 = new Thread (new Consumer (fruitsBuffer), "consumer 3"); p1.start (); c1.start (); c2.start (); c3.start ();} // Producer static class Producer implements Runnable {BlockingQueue  ProductsBuffer; public Producer (BlockingQueue  ProductsBuffer) {this. productsBuffer = productsBuffer;} @ Override public void run () {try {for (int I = 0; I <30; I ++) {System. out. println (Thread. currentThread (). getName () + ": the producer starts to produce the product! "); ProductsBuffer. put (new Fruit ("Fruit:" + I); System. out. println (Thread. currentThread (). getName () + ": This time the production is finished"); Thread. sleep (2000) ;}} catch (InterruptedException e) {e. printStackTrace () ;}} static class Consumer implements Runnable {BlockingQueue  ProductsBuffer; public Consumer (BlockingQueue  ProductsBuffer) {this. productsBuffer = productsBuffer;} @ Override public void run () {while (true) {try {Fruit product = productsBuffer. take (); System. out. println (Thread. currentThread (). getName () + "the product consumed this time is:" + product);} catch (InterruptedException e) {e. printStackTrace () ;}}}// product, Fruit static class Fruit {String name; public Fruit (String name) {this. name = name ;}@ Override public String toString () {return "Fruit {" + "name = '" + name +' \ ''+ '}';}}}     

We can see that one producer shares a blocking queue with three consumers, which is processed correctly no matter whether the data is sent fast or slowly.


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.