阻塞隊列BlockQueue

 先上BlockQueue的源碼:

public interface BlockingQueue<E> extends Queue<E> {

    //增加一個元索 如果隊列已滿,則拋出一個IIIegaISlabEepeplian異常
    boolean add(E e);

    //添加一個元素並返回true 如果隊列已滿,則返回false
    boolean offer(E e);

    //添加一個元素 如果隊列滿,則阻塞
    void put(E e) throws InterruptedException;

    boolean offer(E e, long timeout, TimeUnit unit)
        throws InterruptedException;

    //移除並返回隊列頭部的元素 如果隊列爲空,則阻塞
    E take() throws InterruptedException;

    //移除並返問隊列頭部的元素 如果隊列爲空,則返回null
    E poll(long timeout, TimeUnit unit)
        throws InterruptedException;

    //剩餘容量
    int remainingCapacity();

    //移除並返回隊列頭部的元素 如果隊列爲空,則拋出一個NoSuchElementException異常
    boolean remove(Object o);

    public boolean contains(Object o);

    //一次性從BlockingQueue獲取所有可用的數據對象並轉移到參數集合中
    int drainTo(Collection<? super E> c);

    int drainTo(Collection<? super E> c, int maxElements);
}

可以看到,BlockQueue提供了很多不同於其他集合的方法。下面是它的子類:

我們隨便選一個ArrayBlockQueue來探索一下它是怎麼做到阻塞的。先看看它的三個構造方法:

    public ArrayBlockingQueue(int capacity) {
        this(capacity, false);
    }

    public ArrayBlockingQueue(int capacity, boolean fair) {
        if (capacity <= 0)
            throw new IllegalArgumentException();
        this.items = new Object[capacity];
        lock = new ReentrantLock(fair);
        notEmpty = lock.newCondition();
        notFull =  lock.newCondition();
    }

    public ArrayBlockingQueue(int capacity, boolean fair,
                              Collection<? extends E> c) {
        this(capacity, fair);

        final ReentrantLock lock = this.lock;
        lock.lock(); // Lock only for visibility, not mutual exclusion
        try {
            int i = 0;
            try {
                for (E e : c) {
                    checkNotNull(e);
                    items[i++] = e;
                }
            } catch (ArrayIndexOutOfBoundsException ex) {
                throw new IllegalArgumentException();
            }
            count = i;
            putIndex = (i == capacity) ? 0 : i;
        } finally {
            lock.unlock();
        }
    }

搜嘎,看到了沒,我們關注的重點當然是第三個構造方法,此處用到了lock鎖來把一個普通的集合轉移到ArrayBlockQueue中。ArrayBlockQueue的初始化是在第二個構造方法中完成的。需要注意的是,ArrayBlockQueue內部存儲對象的方式是通過Object數組實現的。

不難想象,構造方法就已經用lock鎖來達到安全的目的了,那麼,其他的阻塞相關方法也肯定離不開lock鎖的影子了。我們帶着這個flag繼續往下走。先來看看offer()方法:

    public boolean offer(E e) {
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            if (count == items.length)
                return false;
            else {
                enqueue(e);
                return true;
            }
        } finally {
            lock.unlock();
        }
    }

果然,被自己的帥氣征服了下。爲了避免被打臉,我們再找幾個驗證下:

    public void put(E e) throws InterruptedException {
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == items.length)
                notFull.await();
            enqueue(e);
        } finally {
            lock.unlock();
        }
    }

    public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == 0)
                notEmpty.await();
            return dequeue();
        } finally {
            lock.unlock();
        }
    }

    public E poll() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return (count == 0) ? null : dequeue();
        } finally {
            lock.unlock();
        }
    }

恩....幸好,沒有被打臉。到這裏,我們就揭開BlockQueue的神祕面紗啦。

發佈了119 篇原創文章 · 獲贊 23 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章