在run()中调用wait()时发生IllegalMonitorStateException [英] IllegalMonitorStateException while calling wait() in run()
问题描述
我创建了一个Java线程,并将堆栈引用传递给它的构造函数, 初始化线程堆栈参考. 在运行方法中,我使用该堆栈对象创建了一个同步块, 在同步块内部运行中调用wait的那一刻,我收到了IllegalMonitorStateException.
I have created an java thread and passed an stack reference to it's constructor, which initialize thread stack reference. In run method i have created an synchronized block with that stack object, the moment am calling wait in run inside synchronized block , i am getting IllegalMonitorStateException.
线程类:
public class Producer extends Thread {
Stack<String> stack=null;
public Producer(Stack<String> stack) {
this.stack=stack;
}
@Override
public void run() {
synchronized (stack) {
if(stack.isEmpty()){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
主类:
public class MainClass {
public static void main(String[] args) {
Stack<String> stack=new Stack<String>();
Producer p=new Producer(stack);
p.start();
}
}
输出:
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:485)
at demo.Producer.run(Producer.java:20)
推荐答案
为使wait()(或notify())正常工作,必须在同一对象上调用它.您现在拥有的与
For wait() (or notify()) to work, you must call it on the same object. What you have now is the same as
synchronized (stack) {
if(stack.isEmpty()){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
相反,您应该这样做
synchronized (stack) {
if(stack.isEmpty()){
try {
stack.wait(); // wait on the same object synchronized.
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
注意:由于等待可能会虚假地唤醒,因此您必须在循环中执行此操作,否则您的方法可能会过早返回.
Note: as wait can wake spuriously you have do this in a loop or your method could return prematurely.
synchronized (stack) {
while (stack.isEmpty()){
try {
stack.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
这篇关于在run()中调用wait()时发生IllegalMonitorStateException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!