PriorityQueue和PriorityBlockingQueue


PriorityQueue和PriorityBlockingQueue

簡介

Queue一般來說都是FIFO的,當然之前我們也介紹過Deque可以做為棧來使用。今天我們介紹一種PriorityQueue,可以安裝對象的自然順序或者自定義順序在Queue中進行排序。

PriorityQueue

先看PriorityQueue,這個Queue繼承自AbstractQueue,是非線程安全的。

PriorityQueue的容量是unbounded的,也就是說它沒有容量大小的限制,所以你可以無限添加元素,如果添加的太多,最后會報OutOfMemoryError異常。

這里教大家一個識別的技能,只要集合類中帶有CAPACITY的,其底層實現大部分都是數組,因為只有數組才有capacity,當然也有例外,比如LinkedBlockingDeque。

只要集合類中帶有comparator的,那么這個集合一定是個有序集合。

我們看下PriorityQueue:

private static final int DEFAULT_INITIAL_CAPACITY = 11;
 private final Comparator<? super E> comparator;

定義了初始Capacity和comparator,那么PriorityQueue的底層實現就是Array,並且它是一個有序集合。

有序集合默認情況下是按照natural ordering來排序的,如果你傳入了 Comparator,則會按照你指定的方式進行排序,我們看兩個排序的例子:

@Slf4j
public class PriorityQueueUsage {

    @Test
    public void usePriorityQueue(){
        PriorityQueue<Integer> integerQueue = new PriorityQueue<>();

        integerQueue.add(1);
        integerQueue.add(3);
        integerQueue.add(2);

        int first = integerQueue.poll();
        int second = integerQueue.poll();
        int third = integerQueue.poll();

        log.info("{},{},{}",first,second,third);
    }

    @Test
    public void usePriorityQueueWithComparator(){
        PriorityQueue<Integer> integerQueue = new PriorityQueue<>((a,b)-> b-a);
        integerQueue.add(1);
        integerQueue.add(3);
        integerQueue.add(2);

        int first = integerQueue.poll();
        int second = integerQueue.poll();
        int third = integerQueue.poll();

        log.info("{},{},{}",first,second,third);
    }
}

默認情況下會按照升序排列,第二個例子中我們傳入了一個逆序的Comparator,則會按照逆序排列。

PriorityBlockingQueue

PriorityBlockingQueue是一個BlockingQueue,所以它是線程安全的。

我們考慮這樣一個問題,如果兩個對象的natural ordering或者Comparator的順序是一樣的話,兩個對象的順序還是固定的嗎?

出現這種情況,默認順序是不能確定的,但是我們可以這樣封裝對象,讓對象可以在排序順序一致的情況下,再按照創建順序先進先出FIFO的二次排序:

public class FIFOEntry<E extends Comparable<? super E>>
        implements Comparable<FIFOEntry<E>> {
    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<E> other) {
        int res = entry.compareTo(other.entry);
        if (res == 0 && other.entry != this.entry)
            res = (seqNum < other.seqNum ? -1 : 1);
        return res;
    }
}

上面的例子中,先比較兩個Entry的natural ordering,如果一致的話,再按照seqNum進行排序。

本文的例子https://github.com/ddean2009/learn-java-collections

歡迎關注我的公眾號:程序那些事,更多精彩等着您!
更多內容請訪問 www.flydean.com


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM