虽然此队列逻辑上是无界的,但是由于资源被耗尽,所以试图执行添加操作可能会失败(导致 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.
|
因此参数timeout和unit没意义,会被忽略掉。
如果需要有序地遍历,则应考虑使用 Arrays.sort(pq.toArray())。
至于使用和别的BlockingQueue(ArrayBlockingQueue,LinkedBlockingQueue)相似,可以参照它们。
注意7 :此类及其迭代器实现了 Collection 和 Iterator 接口的所有可选 方法。