notifyAll()throws IllegalMonitorStateException [英] notifyAll() throws IllegalMonitorStateException
问题描述
private NameFecth nameFetch;
private UseName useName;
private Object nameSetLock;
public static void method {
nameSetLock = new Object()
nameFetch = new NameFetch(nameSetLock);
useName = new UseName(nameSetLock);
Thread nameFetchThread = new Thread(nameFetch);
nameFetchThread.start();
线程useNameThread =新线程(useName);
useNameThread.start();
}
public class NameFetch实现Runnable {
/ *变量和构造函数* /
public void run(){
/ *获取名称并设置变量某种方式* /
synchronized(nameSetLock){
notifyAll();
}
}
}
public class UseName implements Runnable {
/ *变量和构造函数* /
public void run(){
while(!nameBeenSet){
synchronized(nameSetLock){
try {
wait
} catch(InterruptedException e){}
}
}
}
我做错了什么?
> wait 和通知
,无需同步您正在等待或通知的事情。如 Object.notifyAll
中所述:
抛出:
IllegalMonitorStateException
- 如果当前线程不是此对象的监视器的所有者。
这样:
synchronized(nameSetLock){
notifyAll
}
应为:
同步(nameSetLock){
nameSetLock.notifyAll();
}
... and ditto for wait
。请注意,您当前的代码甚至不会编译,因为您使用 syncronized
而不是同步
,这表明您未发布您的实际代码。可能在输入您实际上已更改的代码时,您应该修改问题以更具代表性。
I am designing two threads: one has to get the name of players, and the second thread has to wait for the name being set in order to continue, but notify() all in the first thread is throwing the IllegalMonitorStateException error.
private NameFecth nameFetch;
private UseName useName;
private Object nameSetLock;
public static void method{
nameSetLock = new Object()
nameFetch = new NameFetch(nameSetLock);
useName = new UseName(nameSetLock);
Thread nameFetchThread = new Thread(nameFetch);
nameFetchThread.start();
Thread useNameThread = new Thread(useName);
useNameThread.start();
}
public class NameFetch implements Runnable{
/*variables and constructers*/
public void run(){
/*get name and set the variable somehow*/
synchronized(nameSetLock){
notifyAll();
}
}
}
public class UseName implements Runnable{
/*variables and constructers*/
public void run(){
while(!nameBeenSet){
synchronized(nameSetLock){
try{
wait();
}catch(InterruptedException e) {}
}
}
}
What have I done wrong?
You're calling wait
and notify
without synchronizing on the thing you're waiting on or notifying. As documented in Object.notifyAll
:
Throws:
IllegalMonitorStateException
- if the current thread is not the owner of this object's monitor.
So this:
synchronized(nameSetLock){
notifyAll();
}
should be:
synchronized(nameSetLock){
nameSetLock.notifyAll();
}
... and ditto for wait
. Note that your current code wouldn't even compile as you're using syncronized
rather than synchronized
, which suggests that you didn't post your actual code. It's possible that in typing out the code you've actually changed the problem - in which case you should edit your question to be more representative.
这篇关于notifyAll()throws IllegalMonitorStateException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!