【发布时间】:2019-08-10 05:35:31
【问题描述】:
运行以下代码时,会抛出 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 行,即 wait() 命令时,线程反而退出了可运行状态,它跳转到第 1 行执行,并执行了两次。因此它抛出异常。
我的假设是,在 wait 之后,线程可能已经释放对象的锁(queue)但仍然持有类 ConsumerWaitNotify,这就是它的行为方式。
我已经通过使用 consumeItem() 方法创建一个单独的 Consumer 类来实现我想要的,该方法具有 synchronised(this) 代码和 ConsumerWaitNotify 以 Consumer 对象为成员。
但这有什么问题。我仍然很困惑,无法预测确切的行为。谁能帮帮我?
【问题讨论】:
标签: java multithreading synchronization wait notify