Using Blockingqueue's producer-consumer model

Source: Internet
Author: User

Blockingqueue is a good solution to the problem of how to efficiently and securely "transfer" data in multiple threads. These efficient and thread-safe queue classes provide great convenience for us to quickly build high-quality multi-threaded threads. Use the scene.

First it is a queue, and the role of a queue in the data structure is roughly as follows:

Through a Shared queue, the data can be entered from one end of the queue, output from the other end, and in the producer consumer mode, the data sharing between the two can be easily realized by means of the queue. The powerful blockingqueue makes it unnecessary to worry about when a thread needs to be blocked and when it needs to wake up.

Blockingqueue's core approach:

Put data:

Offer (AnObject) returns False if Blockingqueue can hold and returns TRUE.

Offer (E o,long timeout,timeunit unit), set the wait time, or return failure if you cannot add blockingqueue to the queue within the specified time.

Put (anobject) adds anobject to Blockingqueue, and if Blockqueue has no space, the thread calling this method is blocked until there is space in the blockingqueue to continue.

Get Data:
Poll (time): Take the Blockingqueue in the first row of the object, if not immediately removed, you can wait for the timing of the parameters specified in
Returns null when not taken;
Poll (long timeout, timeunit unit): An object that takes the first team from Blockingqueue, if within a specified time,
Once the queue has data, the data in the queue is returned immediately. Otherwise, the time-out is not well-timed and the return fails.
Take (): Takes the Blockingqueue in the first place of the object, if the blockingqueue is empty, blocking into the waiting state until
Blockingqueue has new data to be added;
Drainto (): Get all available data objects from Blockingqueue at once (you can also specify the number of data to be fetched).
This method can improve the efficiency of data acquisition, and does not need to lock or release multiple times in batches.

Test code:

 PackageBlockingqueue;ImportJava.util.concurrent.ArrayBlockingQueue;ImportJava.util.concurrent.BlockingQueue;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors; Public classBlockingqueuetest { Public Static voidMain (String args[])throwsinterruptedexception{Blockingqueue<String> queue =NewArrayblockingqueue (10); Producer Producer1=NewProducer (queue); Producer Producer2=NewProducer (queue); Producer Producer3=NewProducer (queue); Consumer Consumer=NewConsumer (queue); Executorservice Service=Executors.newcachedthreadpool ();        Service.execute (Producer1);        Service.execute (PRODUCER2);        Service.execute (PRODUCER3);                Service.execute (consumer); Thread.Sleep (10 * 1000);        Producer1.stop ();        Producer2.stop ();                Producer3.stop (); Thread.Sleep (2000); //Exit ExecutorService.shutdown (); }}

Producers:

 PackageBlockingqueue;ImportJava.util.Random;ImportJava.util.concurrent.BlockingQueue;ImportJava.util.concurrent.TimeUnit;ImportJava.util.concurrent.atomic.AtomicInteger; Public classProducerImplementsrunnable{Private volatile BooleanIsRunning =true; PrivateBlockingqueue<string>queue; Private StaticAtomicinteger count =NewAtomicinteger (); Private Static Final intDefault_range_for_sleep = 1000;  PublicProducer (blockingqueue queue) { This. Queue =queue; }         Public voidrun () {String data=NULL; Random R=NewRandom (); System.out.println ("Start producer Threads"); Try{             while(isrunning) {System.out.println ("Producing data ...");                                Thread.Sleep (R.nextint (default_range_for_sleep)); Data= "Data:" +Count.incrementandget (); System.out.println ("Add Data:" + + data + "into queue ..."); if(!queue.offer (data, 2, Timeunit.seconds)) {System.out.println ("Failed to put data:" +data); }            }        }Catch(interruptedexception e) {e.printstacktrace ();        Thread.CurrentThread (). interrupt (); }        finally{System.out.println ("Quit the producer thread!" "); }    }         Public voidStop () {isrunning=false; }        }

Consumers:

 PackageBlockingqueue;ImportJava.util.Random;ImportJava.util.concurrent.BlockingQueue;ImportJava.util.concurrent.TimeUnit; Public classConsumerImplementsrunnable{PrivateBlockingqueue<string>queue; Private Static Final intDefault_range_for_sleep = 1000;  PublicConsumer (blockingqueue<string>queue) {         This. Queue =queue; }         Public voidrun () {System.out.println ("Start consumer thread:"); Random R=NewRandom (); BooleanIsRunning =true; Try{             while(isrunning) {System.out.println ("Getting data from Queue ..."); String Data= Queue.poll (2, Timeunit.seconds); if(NULL!=data) {System.out.println ("Get the data:" +data); System.out.println ("Consuming data:" +data);                Thread.Sleep (R.nextint (default_range_for_sleep)); }Else{isrunning=false; }            }        }Catch(interruptedexception e) {e.printstacktrace ();        Thread.CurrentThread (). interrupt (); }finally{System.out.println ("Quit the consumer thread!" "); }    }}

Reference: http://wsmajunfeng.iteye.com/blog/1629354

Using Blockingqueue's producer-consumer model

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.