运行以下代码时,它会抛出IllegalMonitorStateException。
class Consumer {
private int capacity = 5;
private Queue<Integer> queue = new PriorityQueue<Integer>(capacity);
class ConsumerWaitNotify implements Runnable {
public void run() {
try {
consumeItem();
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
void consumeItem() {
try {
synchronized (queue) { //Line 1
while(queue.size() == 0) {
System.out.format("%n%s: Waiting..Empty Queue, Size: %d%n", Thread.currentThread().getName(),
queue.size());
wait(); //Line 2
}
int popItem = queue.poll();
System.out.format("%n%s: Consumes Item: %d, Size: %d", Thread.currentThread().getName(),
popItem, queue.size());
notify();
}
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ConsWaitNotify {
public static void main(String[] args) {
Consumer pc = new Consumer();
Consumer.ConsumerWaitNotify cwn = pc.new ConsumerWaitNotify();
Thread consumer = new Thread(cwn, "CONSUMER");
consumer.start();
}
}
以下是错误:
CONSUMER: Waiting..Empty Queue, Size: 0
Exception in thread "CONSUMER" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:485)
at com.threadconcurrency.lock.prodcons.Consumer$ConsumerWaitNotify.consumeItem(ConsWaitNotify.java:67)
at com.threadconcurrency.lock.prodcons.Consumer$ConsumerWaitNotify.run(ConsWaitNotify.java:52)
at java.lang.Thread.run(Thread.java:619)
在调试时我发现,当执行第2行ie wait()命令然后线程转出runnable状态时,它会跳转到第1行执行,并执行两次。因此它抛出异常。
我假设在等待之后,线程可能已释放对象(队列)的锁,但仍保留类ConsumerWaitNotify的对象,这就是它的行为。
我通过使用具有synchronized(this)代码的方法consumeItem()和使用Consumer对象作为成员的ConsumerWaitNotify创建单独的Consumer类来实现我想要的。
但这有什么不对。我仍然感到困惑,无法预测确切的行为。谁能帮我吗?
你在变量queue
上同步,但在wait()
对象上调用notify()
和this
。您需要使用synchornized(this)
保持锁定或调用queue.wait()
和queue.notify()
以确保您通知您拥有锁定的同一监视器。你可以看看Guarded Blocks docs。
请注意,您不需要自己实现队列。 JDK提供了一些java.util.concurrent.BlockingQueue
实现:
一个队列,它还支持在检索元素时等待队列变为非空的操作,并在存储元素时等待队列中的空间可用。