1、
package multiThread.art; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * 借助“有界队列”理解 Condition 的使用方式 * * 有界队列:是一种特殊的队列,当队列为空的时候,队列的获取操作将会阻塞获取线程, * 直到队列中有新增元素,当队列已经满了的时候,队列的插入将会阻塞插入线程, * 直到队列出现“空位” * * 补充: 在添加和删除方法中使用 “while 循环”而非“if 判断 ”, * 目的是防止过早或者意外的通知,只有条件符合才能退出循环。 */ public class BoundedQueue<T> { private Object[] items; /** * 添加的下标,删除的下标,数组当前的数量 */ private int addIndex , removeIndex , count; private Lock lock = new ReentrantLock(); Condition notEmpty = lock.newCondition(); Condition notFull = lock.newCondition(); /** * 添加一个元素,如果数组满了,则添加线程进入等待状态,直到有“空位” */ public void add(T t) throws InterruptedException { lock.lock(); try{ while( count == items.length){ notFull.await(); } items[addIndex] = t; if( ++ addIndex == items.length ){ addIndex = 0; } ++count; notEmpty.signal(); }finally { lock.unlock(); } } /** * 由头部删除一个元素,如果数组空,则删除线程进入等待状态,直到有新添加元素 */ public T remove() throws InterruptedException { lock.lock(); try{ while( count == 0 ){ notEmpty.await(); } Object x = items[removeIndex]; if( ++ removeIndex == items.length){ removeIndex = 0; } --count; notFull.signal(); return (T) x; }finally { lock.unlock(); } } }
