[英]IllegalMonitorStateException inside synchronized block
Though I have written wait inside synchronized block. 虽然我已经在同步块中写了等待。 I am getting
IllegalMonitorStateException
. 我正在获取
IllegalMonitorStateException
。 What's the reason then? 那是什么原因
package trials;
public class WaitNotifyTrial {
public static void main(String[] args){
Generator g=new Generator();
g.start();
System.out.println("Start");
synchronized (g) {
try {
g.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("Printing exception");
e.printStackTrace();
}
System.out.println(g.value);
}
}
}
class Generator extends Thread{
int value;
public void run(){
synchronized (this) {
value=10;
}
notify();
}
}
}
These are some of the things wrong with your code: 这些是您的代码有问题的一些地方:
notify()
outside of synchronized (this)
(this is your immediate problem); synchronized (this)
notify()
之外调用notify()
(这是您的直接问题); wait-notify
mechanism on a Thread
instance, which is recommended against in its documentation ; Thread
实例上使用wait-notify
机制, 建议在其文档中使用 ; Thread
instead of using that class as-is and only passing it an instance of your implementation of Runnable
. Thread
而不是按原样使用该类,而仅将Runnable
实现的一个实例传递给它。 For almost a whole decade now, the general advice has been to avoid the wait-notify
mechanism altogether and instead use one of synchronization aids from java.util.concurrent
, such as the CountDownLatch
. 在将近整整十年的时间里,一般的建议是完全避免使用
wait-notify
机制,而应使用java.util.concurrent
一种同步辅助工具,例如CountDownLatch
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.