[英]Notifying a waiting thread on changing a variable
我在努力理解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()
(因此对notifyAll()
也要进行调用)。
下面的代码对您的外部类的实例执行所有操作。
public void refresh(){
synchronized(WhateverYourOuterClass.this){
while(!datachanged){
try {
WhateverYourOuterClass.this.wait();
} catch (InterruptedException ex) {
Exceptions.printStackTrace(ex);
}
}
setRights();
datachanged = false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.