java - 如何理解AtomicInteger里的CAS操作?
PHP中文网
PHP中文网 2017-04-18 10:49:42
0
1
633

下面这个方法,我不理解

public final int getAndIncrement() {
    for (;;) {
        int current = get();
        int next = current + 1;
        if (compareAndSet(current, next))
            return current;
    }
}

为何要循环直到成功?如果这期间有另外的线程更改了value,导致compareAndSet()返回false,那这就表面已经不是原子性了吧,还继续重复有啥意义?

PHP中文网
PHP中文网

认证0级讲师

reply all(1)
左手右手慢动作

It just wants to ensure that the write operation will not be overwritten, and there will be no calculation errors in multi-threaded situations. If you want to achieve atomicity as much as you want, you can only use locks, but this will be inefficient.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!