java同步原子操作_Java在原子操作上同步

不是沒有同步rest()和添加更多的方法。你會遇到你需要更多方法的情況。例如

NamedCounter counter = new NamedCounter();

counter.increment();

// at this exact time (before reaching the below line) another thread might change changed the value of counter!!!!

if(counter.getCount() == 1) {

//do something....this is not thread safe since you depeneded on a value that might have been changed by another thread

}

要解決上面你需要像

NamedCounter counter = new NamedCounter();

if(counter.incrementAndGet()== 1) { //incrementAndGet() must be a synchronized method

//do something....now it is thread safe

}

相反,使用Java的儲存卡,在課堂上的AtomicInteger涵蓋所有情況。或者如果你正在嘗試學習線程安全性,那麼使用AtomicInteger作爲標準(從中學習)。

對於產品代碼,無需考慮兩次就可以與AtomicInteger一起使用!請注意,使用AtomicInteger不會自動保證代碼中的線程安全。你必須使用api提供的方法。他們在那裏是有原因的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值