Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/github/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么在Java中可以在没有竞争条件的情况下并发更新原子变量?_Java_Multithreading_Atomicity - Fatal编程技术网

为什么在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指令)