先看类简介:
/**
* 这是一个队列,当从queue中检索一个元素,或者向queue中插入一个元素的时候,可以进行等待,等待该queue变为非空,及等待queue中有足够的空间可用。
* 等待queue变成非空当检索一个元素,并且等待queue中的空间变为可用当存储一个元素的时候。
* A {@link java.util.Queue} that additionally supports operations
* that wait for the queue to become non-empty when retrieving an
* element, and wait for space to become available in the queue when
* storing an element.
*
* BlockingQueue的所有方法有四种形势,它们以不同的方式处理不能立即满足的操作,但可以在将来的某个时候满足。
* 第一个抛出异常,第二个返回特定的值null或者false,第三个阻塞当前线程直到操作成功,第四个阻塞给定的最大时间,然后放弃。
* <p>{@code BlockingQueue} methods come in four forms, with different ways
* of handling operations that cannot be satisfied immediately, but may be
* satisfied at some point in the future:
* one throws an exception, the second returns a special value (either
* {@code null} or {@code false}, depending on the operation), the third
* blocks the current thread indefinitely until the operation can succeed,
* and the fourth blocks for only a given maximum time limit before giving
* up. These methods are summarized in the following table:
*
* <table BORDER CELLPADDING=3 CELLSPACING=1>
* <caption>Summary of BlockingQueue methods</caption>
* <tr>
* <td></td>
* <td ALIGN=CENTER><em>Throws exception</em></td>
* <td ALIGN=CENTER><em>Special value</em></td>
* <td ALIGN=CENTER><em>Blocks</em></td>
* <td ALIGN=CENTER><em>Times out</em></td>
* </tr>
* <tr>
* <td><b>Insert</b></td>
* <td>{@link #add add(e)}</td>
* <td>{@link #offer offer(e)}</td>
* <td>{@link #put put(e)}</td>
* <td>{@link #offer(Object, long, TimeUnit) offer(e, time, unit)}</td>
* </tr>
* <tr>
* <td><b>Remove</b></td>
* <td>{@link #remove remove()}</td>
* <td>{@link #poll poll()}</td>
* <td>{@link #take take()}</td>
* <td>{@link #poll(long, TimeUnit) poll(time, unit)}</td>
* </tr>
* <tr>
* <td><b>Examine</b></td>
* <td>{@link #element element()}</td>
* <td>{@link #peek peek()}</td>
* <td><em>not applicable</em></td>
* <td><em>not applicable</em></td>
* </tr>
* </table>
*
* BlockingQueue不接受null元素,当尝试添加null的时候,add()/put()/offer()会抛出 NullPointerException异常。null只能作为方法操作失败时的返回值。
* <p>A {@code BlockingQueue} does not accept {@code null} elements.
* Implementations throw {@code NullPointerException} on attempts
* to {@code add}, {@code put} or {@code offer} a {@code null}. A
* {@code null} is used as a sentinel value to indicate failure of
* {@code poll} operations.
*
* BlockingQueue 或许能力有限,在给定的时间,remainingCapacity说明还有这么多的元素可以非阻塞的添加。
* 没有手动指明queue的容量时,该容量为 Integer.MAX_VALUE;
* <p>A {@code BlockingQueue} may be capacity bounded. At any given
* time it may have a {@code remainingCapacity} beyond which no
* additional elements can be {@code put} without blocking.
* A {@code BlockingQueue} without any intrinsic capacity constraints always
* reports a remaining capacity of {@code Integer.MAX_VALUE}.
*
* BlockingQueue 实现主要被用户生产者-消费者队列,但同时还支持 Collection接口。因此,也可以使用remove()来移除队列中的任意元素。
* 然而,这些方法不会被很有效的执行,仅仅偶尔使用,比如取消一个排队的消息。
* <p>{@code BlockingQueue} implementations are designed to be used
* primarily for producer-consumer queues, but additionally support
* the {@link java.util.Collection} interface. So, for example, it is
* possible to remove an arbitrary element from a queue using
* {@code remove(x)}. However, such operations are in general
* <em>not</em> performed very efficiently, and are intended for only
* occasional use, such as when a queued message is cancelled.
*
* BlockingQueue是线程安全的,所有的排队方法自动使用内置锁或其他形式的并发控制。
* 然而,在一个实现中,除非特殊指定,集合的批量操作addAll()/containsAll()/retainAll()/removeAll()不必自动执行。
* 因此,对于addAll(c)操作来说,可能会在只添加一部分元素后就失败抛出异常的情况,即c中的元素没有完全添加。
* <p>{@code BlockingQueue} implementations are thread-safe. All
* queuing methods achieve their effects atomically using internal
* locks or other forms of concurrency control. However, the
* <em>bulk</em> Collection operations {@code addAll},
* {@code containsAll}, {@code retainAll} and {@code removeAll} are
* <em>not</em> necessarily performed atomically unless specified
* otherwise in an implementation. So it is possible, for example, for
* {@code addAll(c)} to fail (throwing an exception) after adding
* only some of the elements in {@code c}.
*
* BlockingQueue不支持close或者shutdown操作来表明不再添加更多的元素。
* 这些特性的需求和使用往往依赖于实现。例如,一个常见的策略是生产者插入特殊的<em>结束流</em>或<em>污染</em>对象,当消费者使用这些对象时,会相应地进行处理。
* <p>A {@code BlockingQueue} does <em>not</em> intrinsically support
* any kind of "close" or "shutdown" operation to
* indicate that no more items will be added. The needs and usage of
* such features tend to be implementation-dependent. For example, a
* common tactic is for producers to insert special
* <em>end-of-stream</em> or <em>poison</em> objects, that are
* interpreted accordingly when taken by consumers.
*
*
* 用法例子:基于典型的生产者-消费者场景,注意 BlockingQueue可以被安全地用于多生产者和多消费者。
* Usage example, based on a typical producer-consumer scenario.
* Note that a {@code BlockingQueue} can safely be used with multiple
* producers and multiple consumers.
* <pre> {@code
* class Producer implements Runnable {
* private final BlockingQueue queue;
* Producer(BlockingQueue q) { queue = q; }
* public void run() {
* try {
* while (true) { queue.put(produce()); }
* } catch (InterruptedException ex) { ... handle ...}
* }
* Object produce() { ... }
* }
*
* class Consumer implements Runnable {
* private final BlockingQueue queue;
* Consumer(BlockingQueue q) { queue = q; }
* public void run() {
* try {
* while (true) { consume(queue.take()); }
* } catch (InterruptedException ex) { ... handle ...}
* }
* void consume(Object x) { ... }
* }
*
* class Setup {
* void main() {
* BlockingQueue q = new SomeQueueImplementation();
* Producer p = new Producer(q);
* Consumer c1 = new Consumer(q);
* Consumer c2 = new Consumer(q);
* new Thread(p).start();
* new Thread(c1).start();
* new Thread(c2).start();
* }
* }}</pre>
*
* 内存一致性影响:就像其他的并发集合,在一个线程中放置一个元素到 BlockingQueue中,同时有另外一个线程,将这个元素从队列中移除。
* <p>Memory consistency effects: As with other concurrent
* collections, actions in a thread prior to placing an object into a
* {@code BlockingQueue}
* <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
* actions subsequent to the access or removal of that element from
* the {@code BlockingQueue} in another thread.
*
* <p>This interface is a member of the
* <a href="{@docRoot}/../technotes/guides/collections/index.html">
* Java Collections Framework</a>.
*
* @since 1.5
* @author Doug Lea
* @param <E> the type of elements held in this collection
*/
从类简介中我们可以看出来有这么7点需要注意:
1、向一个 BlockingQueue中插入或者从中检索一个数据的时候,会进行等待,而且等待可以设置等待的超时时间。
2、 BlockingQueue的所有方法有四种形势,它们以不同的方式处理不能立即满足的操作。
第一个抛出异常,第二个返回特定的值null或者false,第三个阻塞当前线程直到操作成功,第四个阻塞给定的最大时间,然后放弃。
如图:
3、BlockingQueue不接受null元素,当尝试添加null的时候,add()/put()/offer()会抛出 NullPointerException异常。null只能作为方法操作失败时的返回值。
4、 BlockingQueue 存储容量并非无上限,在给定的时间,remainingCapacity指明还有这么多的元素可以非阻塞的添加。 如果没有手动指明queue的容量时,该容量为 Integer.MAX_VALUE;
5、BlockingQueue 实现主要被用户生产者-消费者队列,但同时还支持 Collection接口。因此,也可以使用remove()来移除队列中的任意元素。然而,这些方法不会被很有效的执行,仅仅偶尔使用,比如取消一个排队的消息。
6、 BlockingQueue是线程安全的,所有的排队方法自动使用内置锁或其他形式的并发控制。然而,在一个实现中,除非特殊指定,集合的批量操作addAll()/containsAll()/retainAll()/removeAll()不必自动执行。因此,对于addAll(c)操作来说,可能会在只添加一部分元素后就失败抛出异常的情况,即c中的元素没有完全添加。
7、 BlockingQueue不支持close或者shutdown操作来表明不再添加更多的元素。这些特性的需求和使用往往依赖于自己实现。例如,一个常见的策略是生产者插入特殊的流结束符或者非法污染对象,当消费者使用这些对象时,会相应地进行处理。
8、用法例子:基于典型的生产者-消费者场景,注意 BlockingQueue可以被安全地用于多生产者和多消费者。
9、内存一致性影响:就像其他的并发集合,在一个线程中放置一个元素到 BlockingQueue中,同时有另外一个线程,将这个元素从队列中移除。
类简介介绍完毕。
下边介绍该接口的方法:
public interface BlockingQueue<E> extends Queue<E> {
/**
* 向队列中插入元素,成功返回true,失败抛出 IllegalStateException 异常。
* Inserts the specified element into this queue if it is possible to do
* so immediately without violating capacity restrictions, returning
* {@code true} upon success and throwing an
* {@code IllegalStateException} if no space is currently available.
* When using a capacity-restricted queue, it is generally preferable to
* use {@link #offer(Object) offer}.
*
* @param e the element to add
* @return {@code true} (as specified by {@link Collection#add})
* @throws IllegalStateException if the element cannot be added at this
* time due to capacity restrictions
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this queue
* @throws NullPointerException if the specified element is null
* @throws IllegalArgumentException if some property of the specified
* element prevents it from being added to this queue
*/
boolean add(E e);
/**
* 成功返回true,失败返回false。当用于有容量限制的queue,这个方法通常比add()更好,add()方法失败时只会抛出异常。
* Inserts the specified element into this queue if it is possible to do
* so immediately without violating capacity restrictions, returning
* {@code true} upon success and {@code false} if no space is currently
* available. When using a capacity-restricted queue, this method is
* generally preferable to {@link #add}, which can fail to insert an
* element only by throwing an exception.
*
* @param e the element to add
* @return {@code true} if the element was added to this queue, else
* {@code false}
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this queue
* @throws NullPointerException if the specified element is null
* @throws IllegalArgumentException if some property of the specified
* element prevents it from being added to this queue
*/
boolean offer(E e);
/**
* 向queue中插入指定的元素,当没有足够的空间的时候,会进行等待。
* Inserts the specified element into this queue, waiting if necessary
* for space to become available.
*
* @param e the element to add
* @throws InterruptedException if interrupted while waiting
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this queue
* @throws NullPointerException if the specified element is null
* @throws IllegalArgumentException if some property of the specified
* element prevents it from being added to this queue
*/
void put(E e) throws InterruptedException;
/**
* 向queue中插入指定的元素,当没有足够的空间的时候,会进行等待。等待的时间,按照 timeout指定,单位是 unit,超过等待的时间后,返回false
* TimeUnit 是一个枚举类,包含这些元素:NANOSECONDS ,MICROSECONDS ,MILLISECONDS ,SECONDS ,MINUTES ,HOURS ,DAYS
*
* Inserts the specified element into this queue, waiting up to the
* specified wait time if necessary for space to become available.
*
* @param e the element to add
* @param timeout how long to wait before giving up, in units of
* {@code unit}
* @param unit a {@code TimeUnit} determining how to interpret the
* {@code timeout} parameter
* @return {@code true} if successful, or {@code false} if
* the specified waiting time elapses before space is available
* @throws InterruptedException if interrupted while waiting
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this queue
* @throws NullPointerException if the specified element is null
* @throws IllegalArgumentException if some property of the specified
* element prevents it from being added to this queue
*/
boolean offer(E e, long timeout, TimeUnit unit)
throws InterruptedException;
/**
* 检索并删除队列的头元素,如果需要,会一直等到元素可用
* 等待过程中,如果被干扰,就会抛出 InterruptedException 异常。
* Retrieves and removes the head of this queue, waiting if necessary
* until an element becomes available.
*
* @return the head of this queue
* @throws InterruptedException if interrupted while waiting
*/
E take() throws InterruptedException;
/**
* 检索并删除第一个元素,会等待指定的时间,直到元素变得可用。
* Retrieves and removes the head of this queue, waiting up to the
* specified wait time if necessary for an element to become available.
*
* @param timeout how long to wait before giving up, in units of
* {@code unit}
* @param unit a {@code TimeUnit} determining how to interpret the
* {@code timeout} parameter
* @return the head of this queue, or {@code null} if the
* specified waiting time elapses before an element is available
* @throws InterruptedException if interrupted while waiting
*/
E poll(long timeout, TimeUnit unit)
throws InterruptedException;
/**
* 返回剩余空间大小,如果没有限制,返回 Integer.MAX_VALUE
* Returns the number of additional elements that this queue can ideally
* (in the absence of memory or resource constraints) accept without
* blocking, or {@code Integer.MAX_VALUE} if there is no intrinsic
* limit.
*
* 注意不能依赖这个值来判定一定可以成功插入,因为还要考虑到有其他的线程增加或者删除元素。
* <p>Note that you <em>cannot</em> always tell if an attempt to insert
* an element will succeed by inspecting {@code remainingCapacity}
* because it may be the case that another thread is about to
* insert or remove an element.
*
* @return the remaining capacity
*/
int remainingCapacity();
/**
* 删除队列中的某个元素,如果元素存在多个,则删除一个。
* Removes a single instance of the specified element from this queue,
* if it is present. More formally, removes an element {@code e} such
* that {@code o.equals(e)}, if this queue contains one or more such
* elements.
* Returns {@code true} if this queue contained the specified element
* (or equivalently, if this queue changed as a result of the call).
*
* @param o element to be removed from this queue, if present
* @return {@code true} if this queue changed as a result of the call
* @throws ClassCastException if the class of the specified element
* is incompatible with this queue
* (<a href="../Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if the specified element is null
* (<a href="../Collection.html#optional-restrictions">optional</a>)
*/
boolean remove(Object o);
/**
* 如果队列至少包含指定的一个元素,则返回true
* Returns {@code true} if this queue contains the specified element.
* More formally, returns {@code true} if and only if this queue contains
* at least one element {@code e} such that {@code o.equals(e)}.
*
* @param o object to be checked for containment in this queue
* @return {@code true} if this queue contains the specified element
* @throws ClassCastException if the class of the specified element
* is incompatible with this queue
* (<a href="../Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if the specified element is null
* (<a href="../Collection.html#optional-restrictions">optional</a>)
*/
public boolean contains(Object o);
/**
* 从queue中移除所有的可用元素,并添加到给定的集合中。这个方法比重复调用poll()会更加有效。
* 当尝试添加一个元素到指定的集合中的时候,可能导致该元素同时在两个容器中,或者在这个里边不在另一个里边,或者两个容器中都不存在的错误。
* 如果尝试向自身执行drain操作,会抛出 IllegalArgumentException 异常。而且,当这个操作执行过程中,如果特定的集合发生了改变,行为将会不可知。
* Removes all available elements from this queue and adds them
* to the given collection. This operation may be more
* efficient than repeatedly polling this queue. A failure
* encountered while attempting to add elements to
* collection {@code c} may result in elements being in neither,
* either or both collections when the associated exception is
* thrown. Attempts to drain a queue to itself result in
* {@code IllegalArgumentException}. Further, the behavior of
* this operation is undefined if the specified collection is
* modified while the operation is in progress.
*
* @param c the collection to transfer elements into
* @return the number of elements transferred
* @throws UnsupportedOperationException if addition of elements
* is not supported by the specified collection
* @throws ClassCastException if the class of an element of this queue
* prevents it from being added to the specified collection
* @throws NullPointerException if the specified collection is null
* @throws IllegalArgumentException if the specified collection is this
* queue, or some property of an element of this queue prevents
* it from being added to the specified collection
*/
int drainTo(Collection<? super E> c);
/**
* 操作和drainTo(Collection<? super E> c)相同,只是对迁移的数量进行限制。
* 如何限制呢?从头到尾,只迁移最大数量的元素到指定的集合中?存疑。
* Removes at most the given number of available elements from
* this queue and adds them to the given collection. A failure
* encountered while attempting to add elements to
* collection {@code c} may result in elements being in neither,
* either or both collections when the associated exception is
* thrown. Attempts to drain a queue to itself result in
* {@code IllegalArgumentException}. Further, the behavior of
* this operation is undefined if the specified collection is
* modified while the operation is in progress.
*
* @param c the collection to transfer elements into
* @param maxElements the maximum number of elements to transfer
* @return the number of elements transferred
* @throws UnsupportedOperationException if addition of elements
* is not supported by the specified collection
* @throws ClassCastException if the class of an element of this queue
* prevents it from being added to the specified collection
* @throws NullPointerException if the specified collection is null
* @throws IllegalArgumentException if the specified collection is this
* queue, or some property of an element of this queue prevents
* it from being added to the specified collection
*/
int drainTo(Collection<? super E> c, int maxElements);
}
方法介绍简介:
package java.util.concurrent;
import java.util.Collection;
import java.util.Queue;
public interface BlockingQueue<E> extends Queue<E> {
/**
* 向队列中插入元素,成功返回true,失败抛出 IllegalStateException 异常。
*/
boolean add(E e);
/**
* 成功返回true,失败返回false。当用于有容量限制的queue,这个方法通常比add()更好,add()方法失败时只会抛出异常。
*/
boolean offer(E e);
/**
* 向queue中插入指定的元素,当没有足够的空间的时候,会进行等待。
*/
void put(E e) throws InterruptedException;
/**
* 向queue中插入指定的元素,当没有足够的空间的时候,会进行等待。等待的时间,按照 timeout指定,单位是 unit,超过等待的时间后,返回false
* TimeUnit 是一个枚举类,包含这些元素:NANOSECONDS ,MICROSECONDS ,MILLISECONDS ,SECONDS ,MINUTES ,HOURS ,DAYS
*/
boolean offer(E e, long timeout, TimeUnit unit)
throws InterruptedException;
/**
* 检索并删除队列的头元素,如果需要,会一直等到元素可用
* 等待过程中,如果被干扰,就会抛出 InterruptedException 异常。
*/
E take() throws InterruptedException;
/**
* 检索并删除第一个元素,会等待指定的时间,直到元素变得可用。
*/
E poll(long timeout, TimeUnit unit)
throws InterruptedException;
/**
* 返回剩余空间大小,如果没有限制,返回 Integer.MAX_VALUE
*/
int remainingCapacity();
/**
* 删除队列中的某个元素,如果元素存在多个,则删除一个。
*/
boolean remove(Object o);
/**
* 如果队列至少包含指定的一个元素,则返回true
*/
public boolean contains(Object o);
/**
* 从queue中移除所有的可用元素,并添加到给定的集合中。这个方法比重复调用poll()会更加有效。
* 当尝试添加一个元素到指定的集合中的时候,可能导致该元素同时在两个容器中,或者在这个里边不在另一个里边,或者两个容器中都不存在的错误。
* 如果尝试向自身执行drain操作,会抛出 IllegalArgumentException 异常。而且,当这个操作执行过程中,如果特定的集合发生了改变,行为将会不可知。
*/
int drainTo(Collection<? super E> c);
/**
* 操作和drainTo(Collection<? super E> c)相同,只是对迁移的数量进行限制。
* 如何限制呢?从头到尾,只迁移最大数量的元素到指定的集合中?存疑。
*/
int drainTo(Collection<? super E> c, int maxElements);
}
其他的方法还都是比较明确,只有一个int drainTo(Collection<? super E> c, int maxElements);说的是可以向指定的集合中迁移最大数量的元素,但是迁移的规则并不确定,我们可以进行代码验证:
以ArrayBlockingQueue为例:
public class SoureBlockingQueue {
public static void main(String[] args) {
BlockingQueue<String> bl = new ArrayBlockingQueue<String>(20) ;
for(int i = 0 ;i<20 ;i++){
bl.add(String.valueOf(i));
}
System.out.println(bl);
ArrayList<String> al = new ArrayList<String>();
bl.drainTo(al, 10) ;
System.out.println(bl);
System.out.println(al);
}
}
// 结果:
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
// [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
可以看到,迁移的最大数量的元素,是从头到尾开始进行迁移的,剩余的元素仍然保留在原来的BlockingQueue队列中。
纸上得来终觉浅,绝知此事要躬行,实践出真理,验证得真知,不能怕麻烦。