Java Multithreading (ix) blocking queues

Source: Internet
Author: User

Reprint Please specify source: http://blog.csdn.net/xingjiarong/article/details/48005091

In front of the blog we introduced the use of object lock and conditional lock and more convenient synchronized keyword to achieve multi-threaded synchronization and mutual exclusion, you might think that using the Synchronized keyword is very convenient, However, users must really understand the use of synchronized, and to have a certain degree of multi-threaded programming experience, otherwise it is difficult to do a comprehensive consideration of the problem caused by unexpected problems. In fact, there are more convenient ways in Java than the Synchronized keyword to achieve synchronization and mutual exclusion, and do not need to consider the complex problem, that is to use the blocking queue, this time we will discuss the use of blocking queues.

For example, we often cite the example-bank transfer. Every time we write this program, we have to consider a lot of problems, such as how two threads should be mutually exclusive, the amount is not enough how to do, and so on. In fact, we can solve this problem gracefully and safely through a queue. The transfer thread inserts the transfer instruction object into a queue instead of directly accessing the Bank object. Another thread takes out instructions from the queue to execute the transfer. Because only the thread can access the internal methods of the Bank object, there is no need for synchronization and mutual exclusion.

A blocking queue is when an attempt is made to add an element to the queue and the queue is full, or if you want to move an element out of the queue and the queue is empty, the thread that performs the operation is blocked. Blocking a queue is a useful tool when coordinating multiple threads, and worker threads can periodically store intermediate results in a queue, and other threads move out of the intermediate results for further processing. The queue is automatically load balanced, and when the queue is full, the thread that adds elements to the queue is blocked, and the thread that tries to remove the element from the queue is blocked when the queue is empty.

There are several main blocking queues in Java:

1, Arrayblockingqueue

This type of queue is implemented with a loop array, and there are two ways to construct it:

1) blocking queue with specified capacity

ArrayBlockingQueue(int capacity)

2) blocking queue with specified capacity and fairness settings

ArrayBlockingQueue(int capacity,boolean fair)

The fairness of the blocking queue takes precedence over the longest waiting thread when it wakes up, but this is not guaranteed to be absolutely fair, because a fair blocking queue can be inefficient, so it is not normally used, and by default, a non-fair blocking queue.

2, Linkedblockingqueue

This type of queue is implemented using a list of the following two construction methods:

1) construct an unlimited blocking queue

LinkedBlockingQueue();

2) construct a blocking queue with an upper limit

LinkedBlockingQueue(int capacity);

3, Linkedblockingdeque

This kind of queue construction method and implementation principle can be the second kind, the difference between them is that Linkedblockingdeque is a two-way queue.

4, Delayqueue

Constructs a blocking queue that contains unbounded blocking times with delayed elements. Only those elements that are time-delayed can be removed from the queue.

Construction Method:DelayQueue();

5, Priorityblockingqueue

Priority blocking queues, with high priority removed from the queue first. This queue uses a heap implementation, with the following three construction methods:

PriorityBlockingQueue();PriorityBlockingQueue(int initialCapacity);PriorityBlockingQueue(intsuper E> compaator);

Initialcapacity: The initial capacity of the priority queue. The default value is 11.
Comparator the comparer used to compare elements, and if not specified, the element must implement the comparable interface.

common methods for blocking queues

Method Normal action Actions in special cases
Add Add an Element Throws a IllegalStateException exception if the team is listed as full
Remove Move out and return the head element Throws a Nosuchelementexception exception if the queue is empty
Put Add an Element If the queue is full, block
Take Move out and return the head element If the queue is empty, it blocks
Peek Returns the header element of a queue Returns null if the queue is empty
Poll Move out and return the head element of the queue Returns null if the queue is empty
Element Returns the header element of a queue Throws a Nosuchelementexception exception if the queue is empty
Offer Add an element and return True Returns False if the queue is full

using blocking queues to implement producer consumer issues:

Producer consumer problem is the classic thread synchronization problem, the producer and consumer share a buffer, can be regarded as the warehouse, the producer produces the product to put into the warehouse, the consumer takes out the product in the storehouse to consume, when the storehouse is empty, the consumer is blocked, when the storehouse is full, the producer is blocked.

ImportJava.util.concurrent.ArrayBlockingQueue; Public  class productthread implements Runnable {    PrivateArrayblockingqueue<integer> queue; Public Productthread(arrayblockingqueue<integer> queue) { This. Queue = queue; } Public void Run(){ while(true){Try{intProduct = (int) (Math.random () *Ten);/ * * The queue will block when full * /Queue.put (product); System.out.println (Thread.CurrentThread () +"Production of products--"+product+"remaining elements:"+queue.size ()); Thread.Sleep ( +); }Catch(Exception e)            {E.printstacktrace (); }        }    }}
ImportJava.util.concurrent.ArrayBlockingQueue; Public  class consumethread implements Runnable {    PrivateArrayblockingqueue<integer> queue; Public Consumethread(arrayblockingqueue<integer> queue) { This. Queue = queue; } Public void Run(){ while(true){Try{/ * * Queue is blocked when empty * /                intProduct = Queue.take (); System.out.println (Thread.CurrentThread () +"Consumption of elements--"+product+"remaining space:"+queue.size ()); Thread.Sleep ( +); }Catch(Exception e)            {E.printstacktrace (); }        }    }}
Import Java.util.concurrent.ArrayBlockingQueue; Public classMain { Public Static void Main(string[] args) {//10-size loop array block Queuearrayblockingqueue<integer> queue =NewArrayblockingqueue<> (Ten);/ * * Use 5 producer threads to produce a product */         for(intI=0;i<5; i++) {NewThread (NewProductthread (queue)). Start (); }/ * * Consume products with 2 consumer threads * /         for(intI=0;i<2; i++) {NewThread (NewConsumethread (queue)). Start (); }    }}

Operation Result:

Thread[thread-2,5,main] produced the product--4 remaining elements: 4
Thread[thread-5,5,main] Consumption of elements--1 remaining space: 3
Thread[thread-1,5,main] produced the product--1 remaining elements: 3
Thread[thread-6,5,main] Consumption of elements--1 remaining space: 3
Thread[thread-0,5,main] produced the product--0 remaining elements: 3
Thread[thread-4,5,main] produced the product--1 remaining elements: 3
Thread[thread-3,5,main] produced the product--9 remaining elements: 4
Thread[thread-0,5,main] produced the product--2 remaining elements: 5
Thread[thread-1,5,main] produced the product--9 remaining elements: 5
Thread[thread-4,5,main] produced the product--6 remaining elements: 7
Thread[thread-2,5,main] produced the product--2 remaining elements: 7
Thread[thread-3,5,main] produced the product--1 remaining elements: 7
Thread[thread-5,5,main] Consumption of elements--4 remaining space: 6
Thread[thread-6,5,main] Consumption of elements--0 remaining space: 7
Thread[thread-0,5,main] produced the product--0 remaining elements: 7
Thread[thread-4,5,main] produced the product--7 remaining elements: 8
Thread[thread-3,5,main] produced the product--5 remaining elements: 9
Thread[thread-1,5,main] produced the product--4 remaining elements: 10
Thread[thread-5,5,main] Consumption of elements--9 remaining space: 9
Thread[thread-2,5,main] produced the product--9 remaining elements: 10
Thread[thread-6,5,main] Consumption of elements--2 remaining space: 9
Thread[thread-1,5,main] produced the product--4 remaining elements: 10
Thread[thread-0,5,main] produced the product--3 remaining elements: 10
Thread[thread-6,5,main] Consumption of elements--2 remaining space: 9
Thread[thread-4,5,main] produced the product--5 remaining elements: 10
Thread[thread-5,5,main] Consumption of elements--9 remaining space: 10
Thread[thread-3,5,main] produced the product--9 remaining elements: 10
Thread[thread-5,5,main] Consumption of elements--6 remaining space: 10
Thread[thread-6,5,main] Consumption of elements--1 remaining space: 10
Thread[thread-2,5,main] produced the product--2 remaining elements: 10
Thread[thread-0,5,main] produced the product--1 remaining elements: 10
Thread[thread-5,5,main] Consumption of elements--0 remaining space: 10
Thread[thread-4,5,main] produced the product--4 remaining elements: 10
Thread[thread-6,5,main] Consumption of elements--7 remaining space: 10
Thread[thread-5,5,main] Consumption of elements--5 remaining space: 10

From the results we can see that the initial blocking queue is empty, multiple production lines at the same time, when the product, two consumers began to consume, because the number of producers, so the queue gradually filling up when the queue is full, the producer thread blocked, can only wait for consumers to consume a product before production, So the final appearance of consumption of a product, the production of a product results.

SOURCE Download: http://download.csdn.net/detail/xingjiarong/9052057

Copyright NOTICE: This article for Bo Master original article, reproduced please indicate the source, view the original article, please visit: Http://blog.csdn.net/xingjiarong

Java Multithreading (ix) blocking queues

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.