[Translation] use a blocking queue to solve the producer-consumer problem, queue producer

Source: Internet
Author: User

[Translation] use a blocking queue to solve the producer-consumer problem, queue producer

If you want to avoid using intricatewait-Notify'sStatement, BlockingQueue is very useful.BlockingQueueIt can be used to solve the producer-consumer problem, as shown in the following code example. For every developer, the producer and consumer issues are very familiar. I will not describe them in detail here.

Why? BlockingQueueSuitable for solving producer and consumer problems

Any effective producer-consumer problem solution is implemented by controlling the call of the put () method (production resource) and take () method (consumption Resource) of the producer, once you implement blocking control on the method, you will solve the problem.

JavaBlockingQueueOut-of-the-box support is provided to control the calling of these methods (one thread creates resources and the other consumes resources ).java.util.concurrentPackageBlockingQueueAn interface is a thread-safe queue that can be used to access objects.

BlockingQueue is a data structure that allows one thread to store resources in and the other thread to fetch resources from. This is exactly what producers and consumers need to solve, so let's start to solve this problem.

Use BlockingQueue to solve producer and consumer problems

Use the following code for producer threads:

package cn.edu.hdu.chenpi.cpdemo.howtodoinjava;import java.util.concurrent.BlockingQueue;class Producer implements Runnable {    protected BlockingQueue<Object> queue;    Producer(BlockingQueue<Object> theQueue) {        this.queue = theQueue;    }    public void run() {        try {            while (true) {                Object justProduced = getResource();                queue.put(justProduced);                System.out.println("Produced resource - Queue size now = "                        + queue.size());            }        } catch (InterruptedException ex) {            System.out.println("Producer INTERRUPTED");        }    }    Object getResource() {        try {            Thread.sleep(100); // simulate time passing during read        } catch (InterruptedException ex) {            System.out.println("Producer Read INTERRUPTED");        }        return new Object();    }}

Here, the producer thread creates a resource (Object) and stores it in the queue. If the queue is full (up to 20 ), it will wait until the consumer thread removes resources from the queue, so the queue length will never exceed the maximum value, such as 20.

Consumer

Run the following code for the consumer thread:

package cn.edu.hdu.chenpi.cpdemo.howtodoinjava;import java.util.concurrent.BlockingQueue;class Consumer implements Runnable {    protected BlockingQueue<Object> queue;    Consumer(BlockingQueue<Object> theQueue) {        this.queue = theQueue;    }    public void run() {        try {            while (true) {                Object obj = queue.take();                System.out.println("Consumed resource - Queue size now = "                        + queue.size());                take(obj);            }        } catch (InterruptedException ex) {            System.out.println("CONSUMER INTERRUPTED");        }    }    void take(Object obj) {        try {            Thread.sleep(100); // simulate time passing        } catch (InterruptedException ex) {            System.out.println("Consumer Read INTERRUPTED");        }        System.out.println("Consuming object " + obj);    }}

If there are resources in the queue, the consumer thread will remove the resources from the queue, otherwise it will wait until the producer creates resources.

Test whether the solution is running normally.

Now, let's test whether the above producer consumer threads can work properly:

package cn.edu.hdu.chenpi.cpdemo.howtodoinjava;import java.util.concurrent.BlockingQueue;import java.util.concurrent.LinkedBlockingQueue;public class ProducerConsumerExample {    public static void main(String[] args) throws InterruptedException {        int numProducers = 4;        int numConsumers = 3;        BlockingQueue<Object> myQueue = new LinkedBlockingQueue<>(20);        for (int i = 0; i < numProducers; i++) {            new Thread(new Producer(myQueue)).start();        }        for (int i = 0; i < numConsumers; i++) {            new Thread(new Consumer(myQueue)).start();        }        // Let the simulation run for, say, 10 seconds        Thread.sleep(10 * 1000);        // End of simulation - shut down gracefully        System.exit(0);    }}

When we run the above Code, we will find output results similar to the following:

Consumed resource - Queue size now = 1Produced resource - Queue size now = 1Consumed resource - Queue size now = 1Consumed resource - Queue size now = 1Produced resource - Queue size now = 1Produced resource - Queue size now = 1Produced resource - Queue size now = 1Consuming object java.lang.Object@14c7f728Consumed resource - Queue size now = 0Consuming object java.lang.Object@2b71e323Consumed resource - Queue size now = 0Produced resource - Queue size now = 0Produced resource - Queue size now = 1Produced resource - Queue size now = 2Consuming object java.lang.Object@206dc00bConsumed resource - Queue size now = 1Produced resource - Queue size now = 2Produced resource - Queue size now = 3Consuming object java.lang.Object@1a000bc0Consumed resource - Queue size now = 2Consuming object java.lang.Object@25b6183dConsumed resource - Queue size now = 1Produced resource - Queue size now = 2Produced resource - Queue size now = 3......Produced resource - Queue size now = 20Consuming object java.lang.Object@2b3cd3a6Consumed resource - Queue size now = 19Produced resource - Queue size now = 20Consuming object java.lang.Object@3876982dConsumed resource - Queue size now = 19Produced resource - Queue size now = 20

From the output results, we can find that the queue size will never exceed 20, and the consumer thread consumes the resources produced by the producer.

 

Http://howtodoinjava.com/algorithm/producer-consumer-problem-using-blockingqueue/.

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.