1 class BoundedQueue<T>{
 2     private Object[] items;
 3     //添加的下标、删除的下标、数组当前数量
 4     private int addIndex,removeIndex,count;
 5     private Lock lock = new ReentrantLock();
 6     private Condition conditionProducer= lock.newCondition();
 7     private Condition conditionConsumer = lock.newCondition();
 8     public BoundedQueue(int size){
 9         items = new Object[size];
10     }
11     //添加一个元素,如果数组满,则添加线程进入等待状态,直到有“空位”
12     public void add(T t) throws InterruptedException{
13         lock.lock();
14         try {
15             while (count == items.length)
16                 conditionProducer.await();
17             items[addIndex] = t;
18             if (++addIndex == items.length)
19                 addIndex = 0;
20             ++count;
21             conditionConsumer.signal();
22         }finally {
23             lock.unlock();
24         }
25     }
26     //由头部删除一个元素,如果数组为空,则删除线程进入等待状态,直到有新添加元素
27     @SuppressWarnings("uncheck")//告诉编译器忽略 unchecked 警告信息,如使用List,ArrayList等未进行参数化产生的警告信息
28                                 //可以标注在类、字段、方法、参数、构造方法,以及局部变量上。
29     public T remove() throws InterruptedException{
30         lock.lock();
31         try {
32             while (count == 0)
33                 conditionConsumer.await();
34             Object obj = items[removeIndex];
35             if (++removeIndex == items.length)
36                 removeIndex = 0;
37             --count;
38             conditionProducer.signal();
39             return (T)obj;
40         }finally {
41             lock.unlock();
42         }
43     }
44 }

 

posted on 2017-12-12 16:21  飞奔的菜鸟  阅读(179)  评论(0编辑  收藏  举报