今天找synchronize和reentrantlock区别的时候,发现有个使用reentrantlock中的condition实现有界队列,感觉挺有趣的,自己顺手敲了一遍
class Queue{ private Object[]queue; private int size; //记录队列的大小这样你就不需要累次调用queue.length private int length=0; //用于记录队列中元素的个数 private int addindex=0; private int rmindex=0; private Lock lock= new ReentrantLock(); private Condition full =lock.newCondition(); private Condition empty =lock.newCondition(); public Queue(int size) { this.size=size; queue=new Object[size]; } public void add(Object object) throws InterruptedException { lock.lock(); try { if(length==size) { System.out.println("queue already full"); full.await(); } queue[addindex]=object; length++; if(++addindex == size) addindex=0; empty.signalAll(); } finally { lock.unlock();// TODO: handle finally clause } } public Object remove()throws InterruptedException { lock.lock(); try { if(length==0) { System.out.println("there was nothing to remove"); empty.await(); } Object object=queue[rmindex]; length--; if(++rmindex==size) rmindex=0; full.signalAll(); return object; } finally { lock.unlock(); } }}