public class ArrayBlockingQueueDemo<T> {
private T[] items = (T[]) new Object[100];
private int count,getIndex,putIndex = 0;
private final ReentrantLock lock = new ReentrantLock();
private final Condition notEmpty = lock.newCondition();
private final Condition notFull = lock.newCondition();
private T get(){
lock.lock(); // 先上锁
T obj = null;
while(count == 0){
try {
notEmpty.await();
obj = items[getIndex++];
if(getIndex == items.length) getIndex = 0; //循环队列
--count;
notFull.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
return obj;
}
public void put(T t){
lock.lock();
while(count == items.length){
try {
notFull.await();
items[putIndex++] = t;
if(putIndex == items.length) putIndex = 0;
++count;
notEmpty.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
ArrayBlockingQueueDemo
最新推荐文章于 2022-07-19 15:06:34 发布