PriorityQueue
1.1 特性
- 基于优先堆的无界队列,默认自然排序或者实现Comparator
- 不允许空值,不支持non-comparable,不可比较的对象
- 队列头是基于自然排序的最小元素
-
1.2 属性
private static final int DEFAULT_INITIAL_CAPACITY = 11;/*** Priority queue represented as a balanced binary heap: the two* children of queue[n] are queue[2*n+1] and queue[2*(n+1)]. The* priority queue is ordered by comparator, or by the elements'* natural ordering, if comparator is null: For each node n in the* heap and each descendant d of n, n <= d. The element with the* lowest value is in queue[0], assuming the queue is nonempty.*/transient Object[] queue; // non-private to simplify nested class access/*** The number of elements in the priority queue.*/private int size = 0;/*** The comparator, or null if priority queue uses elements'* natural ordering.*/private final Comparator<? super E> comparator;/*** The number of times this priority queue has been* <i>structurally modified</i>. See AbstractList for gory details.*/transient int modCount = 0; // non-private to simplify nested class access
1.3 重要方法
1.3.1 add&offer
```java //添加到队列末尾
public boolean add(E e) {return offer(e);
}
//插入元素 public boolean offer(E e) { if (e == null) throw new NullPointerException(); modCount++; int i = size; if (i >= queue.length) grow(i + 1); size = i + 1; if (i == 0) queue[0] = e; else siftUp(i, e); return true; }
private void siftUp(int k, E x) {if (comparator != null)siftUpUsingComparator(k, x);elsesiftUpComparable(k, x);}@SuppressWarnings("unchecked")private void siftUpComparable(int k, E x) {Comparable<? super E> key = (Comparable<? super E>) x;// 循环数组进行对比 挨个挪动while (k > 0) {int parent = (k - 1) >>> 1;Object e = queue[parent];if (key.compareTo((E) e) >= 0)break;queue[k] = e;k = parent;}queue[k] = key;}@SuppressWarnings("unchecked")private void siftUpUsingComparator(int k, E x) {while (k > 0) {// 循环数组进行对比 挨个挪动int parent = (k - 1) >>> 1;Object e = queue[parent];if (comparator.compare(x, (E) e) >= 0)break;queue[k] = e;k = parent;}queue[k] = x;}
<a name="xeCGM"></a>### 1.3.2 peek```javapublic E peek() {return (size == 0) ? null : (E) queue[0];}
1.3.3 poll
//出队对头元素,内部是调用 sifDown 挨个前移public E poll() {if (size == 0)return null;int s = --size;modCount++;E result = (E) queue[0];E x = (E) queue[s];queue[s] = null;if (s != 0)siftDown(0, x);return result;}
ConcurrentLinkedQueue
2.1 特性
- 基于链表的无界安全队列,先进先出规则对接点进行排序
- 内部使用CAS的方式进行实现
- https://blog.csdn.net/qq_38293564/article/details/80798310
