二者都是先加鎖ReentrantLock, 依賴於這個鎖的 [出隊]等待隊列 (Condition -> notEmpty)與 【入隊】等待隊列(Condition -> notFull) 來控制。java
鎖默認用的是非公平模式:NonfairSyncnode
能夠這麼理解:數組
拿ArrayBlockingQueue 的出隊來分析:
this
拿LinkedBlockingDeque 的入隊來分析
spa
package com.noob.learn.netty; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; public class Storage { private int capacity = 10; private Queue<Object> queue = new LinkedList<Object>(); final ReentrantLock lock = new ReentrantLock(); /** 當前隊列不是空的,能夠消費 */ private final Condition notEmpty = lock.newCondition(); /** 當前隊列不是滿的, 能夠生產 */ private final Condition notFull = lock.newCondition(); public void produce() { final ReentrantLock lock = this.lock; try { lock.lockInterruptibly(); while (queue.size() > capacity - 1) { System.out.println("庫存量:" + queue.size() + "已滿, 暫時不能執行生產任務!"); notFull.await(); } queue.add(new Object()); System.out.println("生產了, 現倉儲量爲:" + queue.size()); notEmpty.signalAll(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } public void consume() { final ReentrantLock lock = this.lock; try { lock.lockInterruptibly(); while (queue.size() == 0) { System.out.println("庫存量" + queue.size() + "暫時不能執行消費任務!"); notEmpty.wait(); } queue.remove(); System.out.println("消費了, 現倉儲量爲:" + queue.size()); notFull.signalAll(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } public static void main(String[] args) throws InterruptedException { Storage storage = new Storage(); new Thread(() -> { while (true) { storage.produce(); try { Thread.sleep(1000); // 執行太快了降速 } catch (Exception e) { e.printStackTrace(); } } } ).start(); new Thread(() -> { while (true) { storage.consume(); try { Thread.sleep(1000);// 執行太快了降速 } catch (Exception e) { e.printStackTrace(); } } } ).start(); } }
執行結果:
.net