Q1: Could this become a race condition?
是.有点. run()方法可能最终使用过时的refreshMS值.
Q2: If so, what is it the best way to solve this problem?
这最大限度地减少了竞争条件:
class Controller extends Thread implements ConfigurationObserver{
private int refreshMS;
public synchronized void notifyConfiguration(ConfigurationModel config) {
refreshMS = config.getRefreshMs();
}
public void run() {
while (true) {
...
synchronized (this) {
rms = refreshMS;
}
Thread.sleep(rms);
....
}
}
}
如果不在同步块内进行睡眠调用,则无法完全消除竞争条件. (这会导致调用notifyConfiguration的线程阻塞可能无限长的时间.不好主意.)
现在,这一切都很好,但您也应该问自己竞争条件是否可能对应用程序的执行产生有害影响.