为什么在Java中没有竞争条件的情况下可以同时更新原子变量?

时间:2016-08-06 09:00:24

标签: 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 final int incrementAndGet() {
    for (;;) {
        int current = get();
        int next = current + 1;
        if (compareAndSet(current, next))
            return next;
    }
}

我们可以看到current未被同步或锁定,在一个线程获得current之后,另一个线程可能已经更新了current

但似乎原子类在某种程度上避免了竞争条件。

有人可以指出我的错误吗?

1 个答案:

答案 0 :(得分:3)

当且仅当第一个参数等于compareAndSet的当前值时,

AtomicInteger设置值(并返回true)。

也就是说,如果另一个线程已经更改了值,那么current将不会等于当前值,并且循环将再次运行。

来自compareAndSet(int expect, int update)的{​​{3}}:

  

如果是当前值,则以原子方式将值设置为给定的更新值   value ==期望值。