PriorityQueue一個基於優先順序堆的無界優先順序隊列。優先順序隊列的元素按照其自然順序進行排序,或者根據構造隊列時提供的 Comparator 進行排序,具體取決於所使用的構造方法。優先順序隊列不允許使用 null 元素。依靠自然順序的優先順序隊列還不允許插入不可比較的對象(這樣做可能導致 ClassCastException)。
package com.enterise.always.priorityqueue;import java.util.PriorityQueue;import java.util.Random;public class MainAction {public static void main(String[] args) {PriorityQueue<Student> studentQueue = new PriorityQueue<Student>();for (int i = 0; i < 10; i++) {System.out.println("i--->>"+i);studentQueue.add(new Student(new Random().nextInt(100)));}int size = studentQueue.size();for (int j = 0; j < size; j++) {Student s = studentQueue.poll();System.out.println("s--->"+s.getId());}}}
add方法介紹:將指定的元素插入此優先順序隊列。ClassCastException - 如果根據優先順序隊列的順序無法將指定元素與此優先順序隊列中當前元素進行比較。 NullPointerException - 如果指定的元素為 null。所以在add方法中會對要添加的元素進行比較,如果你的優先順序比較高,那麼就排在前面,反之其然。那麼添加的元素如果不一致,那麼就不能進行比較,所以要添加的元素必須實現Comparable介面,或者在構造這個PriorityQueue的時候,要傳進一個指定的比較子進行比較。
源碼實現是:
/** * Inserts the specified element into this priority queue. * * @return {@code true} (as specified by {@link Collection#add}) * @throws ClassCastException if the specified element cannot be * compared with elements currently in this priority queue * according to the priority queue's ordering * @throws NullPointerException if the specified element is null */ 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); else siftUpComparable(k, x); }
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; }
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; }
所以實現優先順序的隊列是在內部對其按照指定的構造器進行排列。
poll方法:擷取並移除此隊列的頭,如果此隊列為空白,則返回 null。
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; }
此對象是線程不安全的,
LinkedBlockingQueue(安全執行緒)