Blocking Scenes
Blockingqueue blocking queues, there are 2 main blocking situations:
1. When the queue is full, the queued operation is blocked
2. When the queue is empty, make a team operation blocking
Blocking queues are primarily used in producer/consumer mode, showing a thread-producing scenario where a thread consumes:
Blockingqueue Interface
Operation |
Throw Exception |
Special Values |
Blocking |
timed out |
Insert |
Add (o) |
Offer (O) |
Put (o) |
Offer (O,timeout,unit) |
Delete |
Remove (o) |
Poll () |
Take () |
Poll (Timeout,unit) |
1. Throw an exception: throws an exception if the operation cannot be performed immediately.
2. Special value: If the operation cannot be done immediately, a special value will be returned, usually true/false.
3. Blocking: If the operation cannot be done immediately, the operation will be blocked.
4. Timeout: If the operation cannot be done immediately, the operation will block the specified time, and if the specified time is not executed, a special value is returned, typically true/false.
You cannot insert null into blockingqueue. Otherwise, the nullpointerexception exception will be reported.
Blockingqueue sub-class
From the above picture you can know that Blockingqueue has the following subclasses:
1. Arrayblockingqueue
2. Delayqueue
3. Linkedblockingqueue
4. Priorityblockingqueue
5. Synchronousqueue
Arrayblockingqueue
A bounded (capacity is limited) blocking queue whose internal implementation is an array. The size of the capacity must be specified at initialization time, and the capacity size cannot be changed once specified. Arrayblockingqueue is to store data in FIFO mode, the most recently inserted object is the tail, and the most recently removed object is the head.
public class Arrayblockingqueue<e> extends abstractqueue<e> implements BLOCKINGQUEUE<E> java.io.Serializable { /** the queued items */ final object[] items; Public Arrayblockingqueue (Int. capacity) public Arrayblockingqueue (Int. capacity, Boolean Fair) public Arrayblockingqueue (int capacity, Boolean fair, collection<? extends e> C)}
Linkedblockingqueue
The configuration of the queue size is optional, if we initially specify a size, it is bounded, if not specified it is no boundary with the default value of integer.max_value capacity, its internal is a linked list.
public class Linkedblockingqueue<e> extends abstractqueue<e> implements BLOCKINGQUEUE<E> java.io.Serializable {public linkedblockingqueue (); public linkedblockingqueue (int capacity); Public Linkedblockingqueue (collection<? extends e> c);}
Priorityblockingqueue
is a queue without boundaries, with the same collation as Prorityqueue, it is important to note that null objects are allowed to be inserted in Priorityblockingqueue.
All objects inserted into the Priorityblockingqueue queue must implement the comparable interface, and the collation of the queue precedence is defined by the implementation of this interface of our team.
In addition Priorityblockingqueue can obtain a iterator, but this iterator does not guarantee the iteration in order of precedence.
Package Org.github.lujiango;import Java.util.iterator;import Java.util.random;import Java.util.concurrent.priorityblockingqueue;class Priorityelement implements Comparable<priorityelement> { private int priority; Public Priorityelement (int.) {this.priority = priority; } @Override public int compareTo (Priorityelement o) {return priority >= o.priority? 1:-1; } @Override Public String toString () {return ' priorityelement[priority= ' + priority + '] '; }}public class Test13 {public static void main (string[] args) throws Interruptedexception {Priorityblockingque ue<priorityelement> queue = new priorityblockingqueue<priorityelement> (); for (int i = 0; i < 5; i++) {Random rand = new Random (); Priorityelement ele = new Priorityelement (Rand.nextint (10)); Queue.put (ele); } System.out.println ("Iterator----------------"); Iterator<priorityeLement> it = Queue.iterator (); while (It.hasnext ()) {System.out.println (It.next ()); } System.out.println ("Priorityblockingqueue.tak ()-----------"); while (!queue.isempty ()) {System.out.println (Queue.take ()); } }}
synchronousqueue
contains only one element, and when a thread inserts an element it is blocked (the thread that placed the element is immediately blocked). Unless this element is consumed by another thread.
Package Org.github.lujiango;import Java.util.concurrent.synchronousqueue;import Java.util.concurrent.TimeUnit; Class MyThread1 implements Runnable { private synchronousqueue<string> queue; Public MyThread1 (synchronousqueue<string> queue) { this.queue = queue; } @Override public Void Run () { try { TimeUnit.SECONDS.sleep (3); System.out.println ("Take a from queue ..."); Queue.take (); } catch (Interruptedexception e) { } }}public class Test14 {public static void Main (string[] args) throws in terruptedexception { synchronousqueue<string> queue = new synchronousqueue<string> (); Thread t = new Thread (new MyThread1 (queue)); T.start (); System.out.println ("Put A into queue ..."); Queue.put ("a");} }
Delayqueue
The Delayqueue block is its inner element, and the elements in the Delayqueue must implement the delayed interface.
Public interface Delayed extends comparable<delayed> { /** * Returns The remaining delay associated with thi S object, in the * given time unit. * * @param unit the time unit * @return the remaining delay; zero or negative values indicate * that the delay has already elapsed * /Long Getdelay (Timeunit unit);}
The Getdelay () return value is the lifetime of the queue element before it is freed, and if <=0 is returned, it means that the element has expired and needs to be freed, and Delayedqueue will release the object through its take () method, such as the No-release (extended element) element. The Take method blocks.
Package Org.github.lujiango;import Java.util.concurrent.delayqueue;import Java.util.concurrent.delayed;import Java.util.concurrent.timeunit;class Delayedelement implements Delayed {private long expired; private long delay; private String name; Public Delayedelement (String name, long delay) {this.name = name; This.delay = delay; This.expired = (delay + system.currenttimemillis ()); } @Override public int compareTo (Delayed o) {delayedelement cache = (delayedelement) o; Return cache.expired > expired? 1:-1; } @Override Public Long getdelay (timeunit unit) {return (Expired-system.currenttimemillis ()); } @Override Public String toString () {return "delayedelement[delay=" + Delay + ", name=" + name + "]"; }}public class Test15 {public static void main (string[] args) throws Interruptedexception {Delayqueue<delay ed> queue = new delayqueue<delayed> (); Delayedelement Ele = new Delayedelement ("3s", 3000); Queue.put (ele); System.out.println (Queue.take ()); }}
Delayqueue are used in many scenarios, such as timed off connections, cache objects, and time-out processing.
Multithreading-blockingqueue,array[linked]blockingqueue,delayqueue,priorityblockingqueue,synchronousqueue