我正在使用 AtomicInteger
来比较和设置同步状态。这是它
private final AtomicInteger state = new AtomicInteger(1);
public void tryDo(){
if(state.compareAndSet(1, 2)){
//do some usefule
}
}
问题是以下情况是否可能:
状态 = 1
- 两个或多个线程尝试将状态
compareAndSet
与2
2.
处的所有线程均失败,状态仍为1
有记录吗?它依赖于平台吗? x86-64
怎么样?
最佳答案
查看契约(Contract) compareAndSet(int expect,int update) :
... False return indicates that the actual value was not equal to the expected value.
因此,暗示,如果只有这些线程正在访问该值,并且您已确认该值当前位于1
,则 < strong>唯一所有失败的原因是NOT位于1
。量子ED。
关于java - 所有线程的compareAndSet 都会失败吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49673683/