我正在尝试使用共享对象和notifyAll()、wait()方法创建一个阻塞队列,但是这段代码会抛出IllegalMonitorStateException异常。我需要在哪里进行更改?
public class BlockingQueueNotifyAll<E> {
private Queue<E> queue;
private int max;
private Object sharedQ = new Object();
public BlockingQueueNotifyAll(int size) {
queue = new LinkedList<>();
this.max = size;
}
public synchronized void put(E e) {
while(queue.size() == max) {
try {
sharedQ.wait();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
queue.add(e);
sharedQ.notifyAll();
}
public synchronized E take() throws InterruptedException {
while(queue.size() == 0) {
sharedQ.wait();
}
E item = queue.remove();
sharedQ.notifyAll();
return item;
}
}