#ArrayBlockQueuejava
//存儲數組 final Object[] items; //取索引 int takeIndex; //插索引 int putIndex; //元素容量 int count; //同步鎖 final ReentrantLock lock; //取阻塞條件 private final Condition notEmpty; //插入阻塞條件 private final Condition notFull;
//lock 優先考慮獲取鎖,待獲取鎖成功後,才響應中斷。 //lockInterruptibly 優先考慮響應中斷,而不是響應鎖的普通獲取或重入獲取 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(); } }