Java concurrent package: blocking queue (BlockingQueue)

http://blog.csdn.net/zxc123e/article/details/51837866 The

article is translated from: http://tutorials.jenkov.com/java-util-concurrent/index.html
took the time to translate the article of this tutorial, and later It will be released one after another. If there is anything wrong, please criticize and correct.
Reprinted from please indicate the source.

The BlockingQueue interface class of BlockingQueue

in the Java.util.concurrent package is a thread-safe queue. In this article we will show how to use BlockingQueue.

This post does not discuss the implementation of BlockQueue. If you are interested, there is a theoretical article Blocking Queues

BlockingQueue usage instructions

BlockingQueue is generally used in such a scenario: one thread produces objects, and another thread consumes objects. The following illustration illustrates this rule:
write image description here
The producer thread will keep producing new objects and inserting them into the queue, up to the maximum limit of objects that the queue can hold.
If the blocking queue reaches its upper limit, the production thread will be blocked if it tries to insert a new object. And the blocking will remain until the consuming thread dequeues an object from the queue.

Likewise, the consuming thread will continue to remove objects from the blocking queue and process them. If a consumer thread tries to remove an object from an empty queue, the consumer thread will be blocked until the producer thread adds an object to the queue.

BlockingQueue method.

The BlockingQueue has 4 types of methods that behave differently for inserting, removing and checking elements in the queue.

operation Throws Exception Special Value Blocks Times Out
Insert add(o) offer(o) put(o) offer(o, timeout, timeunit)
Remove remove(o) poll() take() poll(timeout, timeunit)
Examine element()
The meanings of the four different behaviors of peek() are as follows:

1. Throwing an exception
If the attempted operation is not possible, an exception will be thrown.
2. Special value
If the attempted operation is not possible, a special value will be returned (usually true/false)
3. Blocking
If the attempted operation is not possible, the method will block until it can be executed.
4. Timeout
If the attempted operation is impossible, the method will block until it can be executed, but will not block for more than the given time. And returns a specific value to indicate whether the operation was successful (usually true/false).
You cannot insert null into the BlockingQueue, otherwise a NullPointerException will be thrown.

It is also possible to access arbitrary elements in the BlockingQueue, not just elements at the front and end of the queue. For example, you have queued a pending object (with a queue), but your application needs to cancel the object. At this point you can call the remove(o) method to remove the object from the queue. However, this practice is not efficient and should be avoided unless you really need to.

Implementation of BlockingQueue

Since BlockingQueue is an interface, you need to use its specific implementation class. The java.util.concurrent package contains the following specific implementation of BlockingQueue:

ArrayBlockingQueue
DelayQueue
LinkedBlockingQueue
PriorityBlockingQueue
BlockingQueue Example

The following is an example of the use of BlockingQueue. This example uses a concrete implementation of the BlockingQueued class, ArrayBlockingQueue.

First, the BlockingQueueExample class starts two different threads, Producer and Consumer. The Producer thread inserts strings into the shared BlockingQueue, and the Consumer thread takes them out.

public class BlockingQueueExample {

    public static void main(String[] args) throws Exception {

        BlockingQueue queue = new ArrayBlockingQueue(1024);

        Producer producer = new Producer(queue);
        Consumer consumer = new Consumer(queue);

        new Thread(producer). start();
        new Thread(consumer).start();

        Thread.sleep(4000);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Below Is the Producer class, note that each time the put() method is called, the thread will sleep for 1 second. This will cause the Consumer to block, waiting for the object to be added to the queue.

public class Producer implements Runnable{

    protected BlockingQueue queue = null;

    public Producer(BlockingQueue queue) {
        this.queue = queue;
    }

    public void run() {
        try {
            queue.put("1");
            Thread.sleep(1000);
            queue.put("2");
            Thread.sleep(1000);
            queue.put("3");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Below is the Consumer class. It takes the object from the queue and prints the result.

public class Consumer implements Runnable{

    protected BlockingQueue queue = null;

    public Consumer(BlockingQueue queue) {
        this.queue = queue;
    }

    public void run() {
        try {
            System.out.println(queue.take());
            System.out .println(queue.take());
            System.out.println(queue.take());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
ArrayBlockingQueue

ArrayBlockingQueue is a bounded, blocking queue with elements stored in an internal array. Having bounds means it cannot store infinite elements. There is an upper bound on which elements can be stored at the same time. You can set this upper bound at instantiation time, but the value cannot be changed later.

ArrayBlockingQueue internally stores elements in FIFO (first in, first out) order. The element at the head of the queue will remain in the queue for the longest time. Elements at the tail of the queue will remain in the queue for the shortest time.

Here is how to instantiate and use an ArrayBlockingQueue:

BlockingQueue queue = new ArrayBlockingQueue(1024);

queue.put("1");

Object object = queue.take();
1
2
3
4
5
1
2
3
4
5
Here is one Example of BlockingQueue using generics.

BlockingQueue<String> queue = new ArrayBlockingQueue<String>(1024);

queue.put("1");

String string = queue.take();
1
2
3
4
5
1
2
3
4
5
DelayQueue

DelayQueue internally blocks elements until a certain delay expires. The elements must implement the java.concurrent.Delayed interface. The following is the Delayed interface:

public interface Delayed extends Comparable<Delayed< {

public long getDelay(TimeUnit timeUnit);

}
1
2
3
4
5
1
2
3
4
5
The value returned by the getDelay() method represents the delay time before the element is released. If the return is 0 or a negative number, the delay is considered to be expired or expired, and the element will be released after calling take() and other methods on the DelayQueue.

The TimeUnit instance passed to the getDelay() method is of type Enum, which determines which delay time unit is returned. Possible values ​​for TimeUnit:

DAYS
HOURS
MINUTES
SECONDS
MILLISECONDS
MICROSECONDS
The Delayed interface also extends the java.lang.Comparable interface, and as you can see, this also means that Delayed objects can be compared with each other. This may be used inside a DelayQueue to sort the elements in the queue so that the elements will be released in order when they expire.

Here is an example of how to use DelayQueue:

public class DelayQueueExample {

    public static void main(String[] args) {
        DelayQueue queue = new DelayQueue();

        Delayed element1 = new DelayedElement(); queue.put

        (element1);

        Delayed element2 = queue.take();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
1
2
3
4
5
6
7
8
9
10
11
12
DelayedElement is a concrete implementation of the Delayed interface created by myself, which is not part of the java.util.concurrent package. When you use the DelayQueue class, you must first create a concrete implementation of your own Delayed interface.

LinkedBlockingQueue

LinkedBlockingQueue internally uses a linked list structure to store elements. This linked list structure can have an ideal upper bound. If no upper bound is specified, use Integer.MAX_VALUE as the upper bound.

The internal storage elements of LinkedBlockingQueue follow the rules of FIFO. The element at the head of the queue will remain in the queue for the longest time. Elements at the tail of the queue will remain in the queue for the shortest time.

Here's how to instantiate and use LinkedBlockingQueue:

BlockingQueue<String> unbounded = new LinkedBlockingQueue<String>();
BlockingQueue<String> bounded = new LinkedBlockingQueue<String>(1024);

bounded.put("Value");

String value = bounded.take();









4
5
6
PriorityBlockingQueue

PriorityBlockingQueue is an unbounded concurrent queue. It follows the same rules as the java.util.PriorityQueue class. A null value cannot be inserted into such a queue.

A priority queue is a different kind of queue than a first-in, first-out queue. The element with the highest priority is taken from the queue each time.

PriorityQueue is a new data structure interface provided since JDK1.5.
If no Comparator is provided, the elements in the priority queue are arranged in natural order by default, that is, the number defaults to the smallest at the head of the queue, and the strings are arranged in lexicographical order.
All elements inserted into the PriorityBlockingQueue must implement the java.lang.Comparable interface. So the elements will be sorted according to your Comparable implementation.

Note: PriorityBlockingQueue cannot force the specified elements to have the same priority (compare() == 0).
Also note that if the iterator of PriorityBlockingQueue is reached, the iterator cannot guarantee to iterate by element priority.

Here is an example of how to use PriorityBlockingQueue:

BlockingQueue queue = new PriorityBlockingQueue();

    //String implements java.lang.Comparable
    queue.put("Value");

    String value = queue.take();
1
2
3
4
5
6
1
2
3
4
5
6
SynchronousQueue

A SynchronousQueue is a queue with only a single element inside. A thread that inserts an element into the queue is blocked until another thread removes the element from the queue. Likewise, if a thread tries to fetch an element and there is currently no element, the thread will be blocked until another thread inserts an element into the queue.
Calling this class a queue is a bit of an exaggeration. It's more of a meeting point.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326282744&siteId=291194637