为什么在Java中可以在没有竞争条件的情况下并发更新原子变量?
以下代码在没有竞争条件的情况下工作为什么在Java中可以在没有竞争条件的情况下并发更新原子变量?,java,multithreading,atomicity,Java,Multithreading,Atomicity,以下代码在没有竞争条件的情况下工作 AtomicInteger atomicInt = new AtomicInteger(0); ExecutorService executor = Executors.newFixedThreadPool(20); IntStream.range(0, 1000) .forEach(i -> executor.submit(atomicInt::incrementAndGet)); 下面是incrementAndGet public fi
AtomicInteger atomicInt = new AtomicInteger(0);
ExecutorService executor = Executors.newFixedThreadPool(20);
IntStream.range(0, 1000)
.forEach(i -> executor.submit(atomicInt::incrementAndGet));
下面是incrementAndGet
public final int incrementAndGet() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return next;
}
}
我们可以看到current
未同步或锁定,在一个线程获得current
后,另一个线程可能已经更新了current
但看起来原子类是如何避免竞争条件的
有人能指出我的错误吗?
compareAndSet
当且仅当第一个参数等于AtomicInteger
的当前值时设置值(并返回true)。也就是说,如果另一个线程已经更改了该值,那么
current
将不等于当前值,循环将再次运行
从的比较数据集(int expect,int update)
:
如果当前
value==预期值
compareAndSet()
使用锁定。在大多数实现中,compareAndSet()
将执行一条在硬件中执行锁定的特殊指令(例如x86硬件上的CMPXCHG指令)