原子类自增自减(一个有周期的固定范围值的 AtomicInteger)

发布时间 2023-09-05 10:56:27作者: 每月工资一万八
public class CircularAtomicInteger {
    private final int minValue;
    private final int maxValue;
    private final AtomicInteger atomicInteger;

    public CircularAtomicInteger(int initialValue, int minValue, int maxValue) {
        this.minValue = minValue;
        this.maxValue = maxValue;
        this.atomicInteger = new AtomicInteger(initialValue);
    }
    

    /**
     * 自增
     * @return
     */
    public int incrementAndGet() {
        int currentValue;
        int updatedValue;
        do {
            currentValue = atomicInteger.get();
            updatedValue = currentValue >= maxValue ? minValue : currentValue + 1;
        } while (!atomicInteger.compareAndSet(currentValue, updatedValue));
        return updatedValue;
    }

    /**
     * 自减
     * @return
     */
    public int decrementAndGet() {
        int currentValue;
        int updatedValue;
        do {
            currentValue = atomicInteger.get();
            updatedValue = currentValue <= minValue ? maxValue : currentValue - 1;
        } while (!atomicInteger.compareAndSet(currentValue, updatedValue));
        return updatedValue;
    }
}