java 竞争条件_java – 并发竞争条件?

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的线程阻塞可能无限长的时间.不好主意.)

现在,这一切都很好,但您也应该问自己竞争条件是否可能对应用程序的执行产生有害影响.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值