Detailed explanation of the use of queue interface in Java

The queue interface is at the same level as list and set, and both inherit the collection interface. LinkedList implements the queue interface. The queue interface narrows the access rights to LinkedList methods (that is, if the parameter type in the method is queue, it can only access the methods defined by the queue interface, and can not directly access the non queue methods of LinkedList), so that only appropriate methods can be used. BlockingQueue inherits the queue interface.

Queue is a data structure. It has two basic operations: adding an element at the end of the queue and removing an element from the head of the queue. That is, the queue manages data in a first in first out manner. If you try to add an element to a full blocking queue or remove a element from an empty blocking queue, It will lead to thread blocking. Blocking queue is a very useful tool when multithreading cooperates. Worker threads can periodically store intermediate results in the blocking queue, while other worker threads take them out and modify them in the future. The queue automatically balances the load. If the first thread set runs slower than the second, the second thread set blocks while waiting for the result. If the first thread set runs fast, it will wait for the second thread set to catch up. The following table shows jdk1 Operation of blocking queue in 5:

Add adds a meta index. If the queue is full, an iiiegaislabeeplian exception is thrown. Remove removes and returns the element of the queue head. If the queue is empty, a NoSuchElementException exception is thrown. Element returns the element of the queue head. If the queue is empty, Then a NoSuchElementException exception is thrown. Offer adds an element and returns true. If the queue is full, false poll is returned. Remove and ask the element at the head of the queue. If the queue is empty, null peek is returned. If the queue is empty, null put is returned. Add an element if the queue is full, Take removes and returns the element of the queue header. If the queue is empty, it is blocked

Remove, element, offer, poll and peek actually belong to the queue interface.

Blocking queue operations can be divided into the following three categories according to their response methods: AAD, remove and element operations throw exceptions when you try to add elements to a full queue or get elements from an empty queue. Of course, in a multithreaded program, the queue may become full or empty at any time, so you may want to use the offer, poll, peek methods. These methods only give an error indication without throwing an exception when they cannot complete the task.

Note: the poll and peek methods return null if there is an error. Therefore, it is illegal to insert a null value into the queue.

There are also offer and poll method variants with timeout. For example, the following calls:

An attempt was made to insert an element into the end of the queue within 100 milliseconds. If successful, return true immediately; Otherwise, when the timeout is reached, false is returned. Similarly, call:

If the queue header element is successfully removed within 100 milliseconds, the header element is returned immediately; Otherwise, null is returned when the timeout is reached.

Finally, we have blocking operations put and take. The put method blocks when the queue is full and the take method blocks when the queue is empty.

java. ulil. The concurrent package provides four variants of the blocking queue. By default, the capacity of the linkedblockingqueue has no upper limit (it is inaccurate. If it is not specified, the capacity is integer.max_value. If not, how can it be blocked when put). However, you can also choose to specify its maximum capacity. It is a linked list based queue, which sorts elements according to FIFO (first in first out).

The capacity of arrayblockingqueue needs to be specified during construction, and you can choose whether fairness is required. If the fairness parameter is set to true, The thread with the longest waiting time will be processed first (in fact, this fairness is achieved by setting reentrantlock to true: that is, the thread with the longest waiting time will operate first). Generally, fairness will cost you in performance, and you can only use it when it is really necessary. It is an array based blocking circular queue, which is based on FIFO The (first in, first out) principle sorts elements.

Priorityblockingqueue is a queue with priority, not a first in first out queue. Elements are removed in priority order, The queue also has no upper limit (after looking at the source code, priorityblockingqueue is a repackaging of PriorityQueue, which is based on the heap data structure. PriorityQueue has no capacity limit, just like ArrayList, so it will not be blocked when putting on the priority blocking queue. Although the queue is logically unbounded, attempting to add may lead to failure because the resources are exhausted Outofmemoryerror), but if the queue is empty, the take operation of getting elements will be blocked, so its retrieval operation take is blocked. In addition, the elements entering the queue should have comparison ability.

last, Delayqueue (implemented based on PriorityQueue) is an unbounded blocking queue for storing delayed elements. Elements can be extracted only when the delay expires. The header of the queue is the delayed element with the longest storage time after the delay expires. If the delay has not expired, the queue has no header, and poll will return null. When an element's getdelay When the (timeunit. Nanoseconds) method returns a value less than or equal to zero, the expiration occurs, and the poll removes the element. Null elements are not allowed for this queue. The following is the delay interface:

Java code

The elements placed in the delayqueue will also implement the CompareTo method, which is used by the delayqueue to sort the elements.

The following example shows how to use blocking queues to control thread sets. The program searches all files in a directory and all its subdirectories, and prints out a list of files containing specified keywords. As can be seen from the following examples, two significant advantages of using blocking queues are: no additional synchronization is required when multithreading operates a common queue. In addition, the queue will automatically balance the load, that is, the processing on the other side (production and consumption sides) will be blocked when it is fast, so as to reduce the processing speed gap between the two sides. The following is the specific implementation:

Java code

Original link: http://www.cnblogs.com/end/archive/2012/10/25/2738493.html

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>