下面的代码在没有竞争条件的情况下工作
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
设置值(并返回 true)当且仅当第一个参数等于 AtomicInteger
的当前值时。
也就是说,如果另一个线程已经更改了该值,则 current
将不等于当前值,循环将再次运行。
来自documentation compareAndSet(int expect, int update)
:
Atomically sets the value to the given updated value if the current value == the expected value.
关于java - 为什么在 Java 中可以在没有竞争条件的情况下并发更新原子变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38802457/