但在阻塞队列中,不支持取队首元素操作
以基于数组为例:
即,通过循环队列实现:
class BlockingQueue{
private int[] array = new int[10];
// [head,tail)
// 两者重合时,队列可能为空,也可能为满
private volatile int head = 0;
private volatile int tail = 0;
private volatile int size = 0; // 有效元素个数
/*
-
阻塞队列 入队列
-
为了和普通队列入队列区分,使用 put
-
*/
public void put(int value) throws InterruptedException {
synchronized (this){
// 若队列满了, 阻塞等待, 等下面的出队列操作调用 notify 方法后才可继续执行
if(size == array.length){
wait();
}
array[tail] = value;
tail++;
if(tail == array.length){
tail = 0;
}
size++;
// 唤醒 出队列操作
notify();
}
}
/*
-
阻塞队列 出队列
-
为了和普通队列出队列区分,使用 t
1771



被折叠的 条评论
为什么被折叠?



