我正在努力理解 wait()、notify() 和同步方法的一般用法。我有以下示例,但它不起作用。其他一些对象调用 dataHasChanged()
,这会将实例变量 datachanged
的值更改为 true
。然后,等待线程使用 notifyAll()
检查 datachanged
的值。到目前为止,一切都很好。但是:在 while(!datachanged)
中检查时,datachanged
的值为 false
。因此,我假设 datachanged = true
不知何故未注册到我的 Refresher-Object。我做错了什么?
public synchronized void dataHasChanged(){
datachanged = true;
notifyAll();
}
class Refresher extends SwingWorker<Void, Void>{
public synchronized void refresh(){
while(!datachanged){
try {
wait();
} catch (InterruptedException ex) {
Exceptions.printStackTrace(ex);
}
}
setRights();
datachanged = false;
}
@Override
protected Void doInBackground() throws Exception {
refresh();
return null;
}
@Override
protected void done() {
refresher = new Refresher();
refresher.execute();
}
}
最佳答案
wait()、notify()、notifyAll()
和同步操作每个对象。在您的情况下,refresh() 等待 Refresh 的实例,而 notifyAll()
通知等待外部类实例的所有对象。为此,必须在同一个对象上调用 wait() 和 notifyAll()
(synchronized() 也是如此)。
以下内容对外部类的实例执行所有操作。
public void refresh(){
synchronized(WhateverYourOuterClass.this){
while(!datachanged){
try {
WhateverYourOuterClass.this.wait();
} catch (InterruptedException ex) {
Exceptions.printStackTrace(ex);
}
}
setRights();
datachanged = false;
}
}
关于java - 通知等待线程更改变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21882403/