Use of the "Java Concurrency" blocking queue

Source: Internet
Author: User

In a previous blog called conditional blocking condition, a overstating example was mentioned: using condition to implement a blocking queue. In fact, in Java, there is a called ArrayBlockingQueue<E> class that provides the ability to block queues, so if we need to use a blocking queue, there is absolutely no need to write on their own.
  ArrayBlockingQueue<E>Achieved BlockingQueue<E> , there are also LinkedBlockingQueue<E> and PriorityBlockingQueue<E> . is mainly based on the implementation of the ArrayBlockingQueue<E> array, LinkedBlockingQueue<E> is based on the chain list, they are first-out, and PriorityBlockingQueue<E> is based on the priority queue. This blog post is mainly used for ArrayBlockingQueue<E> example, the other two ways of use and ArrayBlockingQueue<E> almost, specific can refer to official documents.
It is ArrayBlockingQueue<E> necessary to indicate the size of the buffer, indicate that it cannot be modified, attempt to put an element into the full queue, cause the operation to be blocked, and attempt to extract elements from the empty queue will cause similar blocking. Use ArrayBlockingQueue<E> the following to implement a feature similar to the one mentioned in the previous blog post:

 Public  class blockingqueuetest {     Public Static void Main(string[] args) {Finalblockingqueue<integer> queue =NewArrayblockingqueue<integer> (3);//Buffer allows 3 data to be placed         for(inti =0; I <2; i + +) {NewThread () {//Open two threads to keep data in buffer                @Override                 Public void Run() { while(true) {Try{Thread.Sleep (Long) (Math.random () * +)); System.out.println (Thread.CurrentThread (). GetName () +"Ready to put the data"+ (queue.size () = =3?".. Queue is full, waiting for ":"...")); Queue.put (1); System.out.println (Thread.CurrentThread (). GetName () +"deposit data,"+"Queue currently has"+ queue.size () +"a data"); }Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace ();        }}}}.start (); }NewThread () {//Open a thread that keeps fetching data from the buffer            @Override             Public void Run() { while(true) {Try{Thread.Sleep ( +); System.out.println (Thread.CurrentThread (). GetName () +"Ready to fetch data"+ (queue.size () = =0?".. Queue is empty, waiting for ":"..."));                        Queue.take (); System.out.println (Thread.CurrentThread (). GetName () +"Take out the data,"+"Queue currently has"+ queue.size () +"a data"); }Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace ();    }}}}.start (); }}

The logic of the program is simple, not difficult to understand, the following look at the results of the operation:

Thread-0 ready to put data ...
Thread-0 data, queue currently has 1 data
Thread-1 ready to put data ...
Thread-1 data, queue currently has 2 data
Thread-2 ready to fetch data ...
Thread-2 out the data, the queue currently has 1 data
Thread-0 ready to put data ...
Thread-0 data, queue currently has 2 data
Thread-1 ready to put data ...
Thread-1 data, queue currently has 3 data
Thread-2 ready to fetch data ...
Thread-2 out the data, the queue currently has 2 data
Thread-0 ready to put data ...
Thread-0 data, queue currently has 3 data
Thread-1 ready to put data. Queue is full, waiting
Thread-0 ready to put data. Queue is full, waiting
Thread-2 ready to fetch data ...
Thread-2 out the data, the queue currently has 2 data
Thread-1 data, queue currently has 3 data

So the use of blocking queues is very convenient, we do not have to make a judgment.
Previously introduced in the blog thread communication can use synchronized and wait, notify combination, you can use the condition, in fact, we can also use blocking queue to implement inter-thread communication, here is an example:

//Blocking queues for inter-thread communication Public  class blockingqueuecommunication {     Public Static void Main(string[] args) {Business bussiness =NewBusiness ();NewThread (NewRunnable () {//Open a sub-thread                    @Override                     Public void Run() { for(inti =1; I <=3;                        i++) {bussiness.sub (); }}). Start ();//Main method main thread         for(inti =1; I <=3;        i++) {bussiness.main (); }}}class Business {Private inti =0; Blockingqueue queue1 =NewArrayblockingqueue (1); Blockingqueue queue2 =NewArrayblockingqueue (1); {Try{Queue2.put (1); }Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); }    } Public void Sub() {Try{Queue1.put (1);//If the main thread is not finished, the sub-thread buffer is always number and the child thread is blocked here}Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); } System.out.println ("i= before the child thread executes"+ i++); System.out.println ("i= after a child thread executes"+ i);Try{Queue2.take ();//Remove the number of buffers in the main thread to allow the main thread to execute}Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); }    } Public void Main() {Try{Queue2.put (1);//If the child thread is not finished, the main thread buffer is always number and the main thread is blocked here}Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); } System.out.println ("main thread execution before i="+ i++); System.out.println ("i= after main thread execution"+ i);Try{Queue1.take ();//Remove the number of buffers in the child thread and let the child threads execute}Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); }    }}

The code looks a bit long, but the logic is simple, that is, the main thread and the sub-thread. You take me a moment, rotate, perform the task is to increase the public data I from 1, using the blocking queue implementation, and thread safety, because one thread executes, another thread is blocked.
The idea is to define two blocking queues, which can only have 1 numbers, respectively, corresponding to two threads. Then I fill the main thread's queue in a static code block, and then I let two threads plug a number into their respective queue before executing the task, so I'm sure the main thread must be blocked, because I've already plugged a number of the main thread's queue in the static code block. Then the child thread takes out the number of the main thread queue after executing the task, then the main thread starts executing, and the child thread is blocked (because the number is plugged before it executes its own task), the main thread executes the number in the queue of the child thread, and the child thread begins to execute. So the blocking queue is used to block a thread to implement alternating between two threads.
For the use of blocking queues, summarize so much!
  

Related reading: http://blog.csdn.net/column/details/bingfa.html

-Willing to share and progress together!
-More articles please see: http://blog.csdn.net/eson_15

Use of the "Java Concurrency" blocking queue

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.