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的全部内容,更多相关ArrayBlockingQueueDemo内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复