Java: Atomic Variables

https://www.baeldung.com/java-atomic-variables
对于不同线程读取同一个变量这样的逻辑,直接用锁需要暂停+resume threads,比较昂贵,Atomic Operations在此时能够起到线程安全同时又不需要如此高昂的代价的作用。

public class SafeCounterWithoutLock {
    private final AtomicInteger counter = new AtomicInteger(0);
    
    public int getValue() {
        return counter.get();
    }
    public void increment() {
        while(true) {
            int existingValue = getValue();
            int newValue = existingValue + 1;
            if(counter.compareAndSet(existingValue, newValue)) {
                return;
            }
        }
    }
}
原文地址:https://www.cnblogs.com/xuesu/p/14291889.html