我为 Prod-Cons 问题编写了一个简单的阻塞队列示例。下面的例子不起作用;除非我将入队/出队逻辑的添加/删除部分与等待线程上的通知交换。在 BlockingQueue 的任何实现中,我都找不到对这种行为的任何明确解释。在入队部分,添加元素然后通知不应该是正确的吗?这样我可以保证当消费者线程运行时,它应该有一个元素给消费者,并且不会返回null。请解释。
import java.util.LinkedList;
import java.util.Queue;
public class BlockingQueueCustom<T> {
private int size = 10;
private Queue<T> queue = new LinkedList<T>();
public BlockingQueueCustom(int s) {
this.size = s;
}
public synchronized void enqueue(T element) throws InterruptedException {
while (queue.size() == size) {
wait();
}
queue.add(element); //Comment this part to make it work
if (queue.size() == 0) {
this.notifyAll();
}
//queue.add(element); Uncommenting this will make it work
}
public synchronized T dequeue() throws InterruptedException {
while (queue.size() == 0) {
this.wait();
}
T element = queue.remove(); //Comment this part to make it work
if (queue.size() == size) {
this.notifyAll();
}
return element; //Comment this part to make it work
//return queue.remove(); Uncommenting this will make it work
}
}