java隊列,ArrayBlockingQueue

提供了三個構造方法:數組

   ①.ArrayBlockingQueue(int capacity)//指定長度,默認加鎖機制爲非公平鎖this

   ②.ArrayBlockingQueue(int capacity, boolean fair)//顯示指定使用公平鎖或非公平鎖線程

   ③.ArrayBlockingQueue(int capacity, boolean fair,Collection<? extends E> c) //能夠傳入一個集合code

全局變量:對象

 final Object[] items;//queue維護了一個定長數組用來當對象容器,在初始化時建立
 int takeIndex;
 int putIndex;
 int count;//容器的大小隊列

 final ReentrantLock lock;//顯示鎖
 private final Condition notEmpty;//用來作線程通訊,若隊列已空則阻塞ci

 private final Condition notFull;//判斷是否已滿,滿則阻塞it

方法:io

/**添加**/
 public void put(E e) throws InterruptedException {
        checkNotNull(e);//非空檢查,若爲空拋異常
        final ReentrantLock lock = this.lock;//加鎖
        lock.lockInterruptibly();
        try {
            while (count == items.length)
                notFull.await();//隊列滿了阻塞.
            insert(e);//不然添加
        } finally {
            lock.unlock();
        }
    }

private void insert(E x) {
        items[putIndex] = x;
        putIndex = inc(putIndex);
        ++count;
        notEmpty.signal();//喚醒消費線程
    }


 final int inc(int i) {//返回下一個該添加的位置,若滿則從0開始
        return (++i == items.length) ? 0 : i;
    }


 /**取**/
 public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == 0)
                notEmpty.await();//沒有可消費對象阻塞
            return extract();//獲取
        } finally {
            lock.unlock();
        }
    }

private E extract() {
        final Object[] items = this.items;
        E x = this.<E>cast(items[takeIndex]);//獲取一個強轉對象
        items[takeIndex] = null;/清除容器中這個元素
        takeIndex = inc(takeIndex);//下一個可取的位置
        --count;
        notFull.signal();//喚醒生產線程
        return x;
    }

以上是幾個經常使用的方法, 其餘方法差異不大.ast

相關文章
相關標籤/搜索