java.lang.IllegalMonitorStateException:对象在等待()之前未被线程锁定
你很接近,但你错过了一些同步。要做wait()
或者notify()
你需要在一个synchronized
街区。
如果您想编写一个返回某些值的任务,我会执行以下操作。将结果存储在一个字段中,在synchronized
onComplete()
oronFail()
方法中更新该字段。然后,您的调用线程可以使用该waitForResult()
方法在完成后将其返回。
public class MyTask implements Task {
private String result;
public synchronized void onComplete() {
result = "it worked";
// this is allowed because the method is synchronized
notify();
}
public synchronized void onFail() {
result = "it failed";
// this is allowed because the method is synchronized
notify();
}
public synchronized String waitForResult() {
// a while loop is a good pattern because of spurious wakeups
// also, it's important to realize that the job might have already
// finished so we should always test it _before_ we wait
while (result == null) {
wait();
}
return result;
}
}
正在测试所有内容以完成的线程只需要执行以下操作:
String result = myTask.waitForResult();
希望这可以帮助。