现在的位置: 首页 > 综合 > 正文

PriorityBlockingQueue

2012年04月14日 ⁄ 综合 ⁄ 共 2125字 ⁄ 字号 评论关闭

 一个无界的阻塞队列,它使用与类PriorityQueue相同的顺序规则,并且提供了阻塞检索的操作。

 虽然此队列逻辑上是无界的,但是由于资源被耗尽,所以试图执行添加操作可能会失败(导致 OutOfMemoryError)。

 此类不允许使用 null 元素。依赖自然顺序的优先级队列也不允许插入不可比较的对象(因为这样做会抛出 ClassCastException)。

Operations on this class make no guarantees about the ordering of elements with equal priority. If you need to enforce an ordering, you can define custom classes or comparators that use a secondary key to break ties in primary priority values. For example,
here is a class that applies first-in-first-out tie-breaking to comparable elements. To use it, you would insert a new FIFOEntry(anEntry) instead of a plain entry object.

 class FIFOEntry<  super=""  e=""  >>
     
implements Comparable> {
   
static final AtomicLong seq = new AtomicLong(0);
   
final long seqNum;
   
final E entry;
   
public FIFOEntry(E entry) {
     seqNum
= seq.getAndIncrement();
     
this.entry = entry;
   

   
public E getEntry() { return entry; }
   
public int compareTo(FIFOEntry other) {
     
int res = entry.compareTo(other.entry);
     
if (res == 0 && other.entry != this.entry)
       res
= (seqNum < other.seqNum ? -1 : 1);
     
return res;
   
}
 
}}

构造函数

Public Constructors
PriorityBlockingQueue()
Creates a PriorityBlockingQueue with the default initial capacity (11) that orders its elements according to their natural
ordering
.
PriorityBlockingQueue(int
initialCapacity)
Creates a PriorityBlockingQueue with the specified initial capacity that orders its elements according to their natural
ordering
.
PriorityBlockingQueue(int
initialCapacity, Comparator<? super E> comparator)
Creates a PriorityBlockingQueue with the specified initial capacity that orders its elements according to the specified comparator.
PriorityBlockingQueue(Collection<? extends E>
c)
Creates a PriorityBlockingQueue containing the elements in the specified collection.
注意1:它是无界阻塞队列,容量是无限的,它使用与类PriorityQueue相同的顺序规则。

 注意2:它是线程安全的,是阻塞的

 注意3:不允许使用 null 元素。 

 注意4:对于put(E o)和offer(E o, long timeout, TimeUnit unit),由于该队列是无界的,所以此方法永远不会阻塞。

 因此参数timeout和unit没意义,会被忽略掉。

 注意5:iterator() 方法中所提供的迭代器并不保证以特定的顺序遍历 PriorityBlockingQueue 的元素。

 如果需要有序地遍历,则应考虑使用 Arrays.sort(pq.toArray())。 

 注意6:关于PriorityBlockingQueue的排序原理请参照《
PriorityQueue
 至于使用和别的BlockingQueue(ArrayBlockingQueue,LinkedBlockingQueue)相似,可以参照它们。

 注意7:此类及其迭代器实现了 Collection 和 Iterator 接口的所有可选 方法。
关于PriorityBlockingQueue的使用请参考《ArrayBlockingQueue》和《BlockingQueue

抱歉!评论已关闭.