ArrayBlockingQueue

enqueue

// putindex認(rèn)為是寫入的索引
private void enqueue(E x) {
    // assert lock.getHoldCount() == 1;
    // assert items[putIndex] == null;
    final Object[] items = this.items;
    // 入隊(duì)到putIndex的位置
    items[putIndex] = x;
    // 如果putIndex已經(jīng)到隊(duì)尾,那么重置從頭開始
    if (++putIndex == items.length)
        putIndex = 0;
    count++;
    // 入隊(duì),當(dāng)然notEmpty條件已經(jīng)滿足,需要喚醒
    notEmpty.signal();
}

dequeue

// takeindex認(rèn)為是讀取的索引
private E dequeue() {
    // assert lock.getHoldCount() == 1;
    // assert items[takeIndex] != null;
    final Object[] items = this.items;
    @SuppressWarnings("unchecked")
    // 拿到takeIndex的值賦予x
    E x = (E) items[takeIndex];
    // 設(shè)置takeIndex位置為null
    items[takeIndex] = null;
    // 如果takeindex已經(jīng)到末尾,那么從頭開始
    if (++takeIndex == items.length)
        takeIndex = 0;
    count--;
    if (itrs != null)
        itrs.elementDequeued();
    // 出隊(duì)的結(jié)果,數(shù)組未滿已經(jīng)滿足,需要喚醒
    notFull.signal();
    return x;
}

offer

public boolean offer(E e) {
    checkNotNull(e);
    final ReentrantLock lock = this.lock;
    // 獨(dú)占鎖加鎖
    lock.lock();
    try {
        // 如果數(shù)組滿,那么直接返回
        if (count == items.length)
            return false;
        else {
            // 否則入隊(duì)
            enqueue(e);
            return true;
        }
    } finally {
        lock.unlock();
    }
}

put

public void put(E e) throws InterruptedException {
    checkNotNull(e);
    final ReentrantLock lock = this.lock;
    // 獨(dú)占鎖加鎖,且可中斷
    lock.lockInterruptibly();
    try {
        // 自旋等待數(shù)組未滿為止
        while (count == items.length)
            notFull.await();
        // 入隊(duì)
        enqueue(e);
    } finally {
        lock.unlock();
    }
}

poll

public E poll() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        // 如果數(shù)組為空,返回null
        // 否則出隊(duì)
        return (count == 0) ? null : dequeue();
    } finally {
        lock.unlock();
    }
}

take

public E take() throws InterruptedException {
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        // 自旋等待數(shù)組不為空為止,出隊(duì)
        while (count == 0)
            notEmpty.await();
        return dequeue();
    } finally {
        lock.unlock();
    }
}

peek

public E peek() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        // 直接返回takeIndex位置的值,但并不移除它
        return itemAt(takeIndex); // null when queue is empty
    } finally {
        lock.unlock();
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容