PriorityQueue

1.1 特性

  • 基于优先堆的无界队列,默认自然排序或者实现Comparator
  • 不允许空值,不支持non-comparable,不可比较的对象
  • 队列头是基于自然排序的最小元素
  • 非线程安全的

    1.2 属性

    1. private static final int DEFAULT_INITIAL_CAPACITY = 11;
    2. /**
    3. * Priority queue represented as a balanced binary heap: the two
    4. * children of queue[n] are queue[2*n+1] and queue[2*(n+1)]. The
    5. * priority queue is ordered by comparator, or by the elements'
    6. * natural ordering, if comparator is null: For each node n in the
    7. * heap and each descendant d of n, n <= d. The element with the
    8. * lowest value is in queue[0], assuming the queue is nonempty.
    9. */
    10. transient Object[] queue; // non-private to simplify nested class access
    11. /**
    12. * The number of elements in the priority queue.
    13. */
    14. private int size = 0;
    15. /**
    16. * The comparator, or null if priority queue uses elements'
    17. * natural ordering.
    18. */
    19. private final Comparator<? super E> comparator;
    20. /**
    21. * The number of times this priority queue has been
    22. * <i>structurally modified</i>. See AbstractList for gory details.
    23. */
    24. transient int modCount = 0; // non-private to simplify nested class access

    1.3 重要方法

    1.3.1 add&offer

    ```java //添加到队列末尾
    public boolean add(E e) {

    1. 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; }

  1. private void siftUp(int k, E x) {
  2. if (comparator != null)
  3. siftUpUsingComparator(k, x);
  4. else
  5. siftUpComparable(k, x);
  6. }
  7. @SuppressWarnings("unchecked")
  8. private void siftUpComparable(int k, E x) {
  9. Comparable<? super E> key = (Comparable<? super E>) x;
  10. // 循环数组进行对比 挨个挪动
  11. while (k > 0) {
  12. int parent = (k - 1) >>> 1;
  13. Object e = queue[parent];
  14. if (key.compareTo((E) e) >= 0)
  15. break;
  16. queue[k] = e;
  17. k = parent;
  18. }
  19. queue[k] = key;
  20. }
  21. @SuppressWarnings("unchecked")
  22. private void siftUpUsingComparator(int k, E x) {
  23. while (k > 0) {
  24. // 循环数组进行对比 挨个挪动
  25. int parent = (k - 1) >>> 1;
  26. Object e = queue[parent];
  27. if (comparator.compare(x, (E) e) >= 0)
  28. break;
  29. queue[k] = e;
  30. k = parent;
  31. }
  32. queue[k] = x;
  33. }
  1. <a name="xeCGM"></a>
  2. ### 1.3.2 peek
  3. ```java
  4. public E peek() {
  5. return (size == 0) ? null : (E) queue[0];
  6. }

1.3.3 poll

  1. //出队对头元素,内部是调用 sifDown 挨个前移
  2. public E poll() {
  3. if (size == 0)
  4. return null;
  5. int s = --size;
  6. modCount++;
  7. E result = (E) queue[0];
  8. E x = (E) queue[s];
  9. queue[s] = null;
  10. if (s != 0)
  11. siftDown(0, x);
  12. return result;
  13. }

ConcurrentLinkedQueue

2.1 特性