专业的JAVA编程教程与资源

网站首页 > java教程 正文

Java AtomicInteger操作详解(java attachment)

temp10 2025-07-19 22:32:18 java教程 3 ℃ 0 评论

介绍

AtomicInteger 是使用CAS实现的对 int 类型进行原子操作的类。

什么是CompareAndSwap(CAS? 即比较并替换,实现并发算法时常用到的一种技术。CAS操作包含三个操作数——内存位置、预期原值及新值。执行CAS操作的时候,将内存位置的值与预期原值比较,如果相匹配,那么处理器会自动将该位置值更新为新值,否则,处理器不做任何操作。CAS是一条CPU的原子指令(cmpxchg指令),不会造成所谓的数据不一致问题,AtomicBoolean 调用 Unsafe 类提供的CAS方法(如compareAndSwapXXX)实现了原子操作。要了解 Unsafe 的基本运用,请查看 《Unsafe的基本操作》

Java AtomicInteger操作详解(java attachment)

基本操作

AtomicInteger 具有与 AtomicBoolean 相同的方法,如下:

/**
 * Gets the current value.
 *
 * @return the current value
 */
public final int get() {
    return value;
}

/**
 * Sets to the given value.
 *
 * @param newValue the new value
 */
public final void set(int newValue) {
    value = newValue;
}

/**
 * Eventually sets to the given value.
 *
 * @param newValue the new value
 * @since 1.6
 */
public final void lazySet(int newValue) {
    unsafe.putOrderedInt(this, valueOffset, newValue);
}

/**
 * Atomically sets to the given value and returns the old value.
 *
 * @param newValue the new value
 * @return the previous value
 */
public final int getAndSet(int newValue) {
    return unsafe.getAndSetInt(this, valueOffset, newValue);
}

/**
 * Atomically sets the value to the given updated value
 * if the current value {@code ==} the expected value.
 *
 * @param expect the expected value
 * @param update the new value
 * @return {@code true} if successful. False return indicates that
 * the actual value was not equal to the expected value.
 */
public final boolean compareAndSet(int expect, int update) {
    return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}

/**
 * Atomically sets the value to the given updated value
 * if the current value {@code ==} the expected value.
 *
 * <p><a href="package-summary.html#weakCompareAndSet">May fail
 * spuriously and does not provide ordering guarantees</a>, so is
 * only rarely an appropriate alternative to {@code compareAndSet}.
 *
 * @param expect the expected value
 * @param update the new value
 * @return {@code true} if successful
 */
public final boolean weakCompareAndSet(int expect, int update) {
    return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}

此部分操作请查看《AtomicBoolean操作详解及原理分析》

1、getAndIncrement

将当前值加1,并返回加1前的值。

AtomicInteger atomicInteger = new AtomicInteger(1);
int getAndIncrement = atomicInteger.getAndIncrement();
int currentValue = atomicInteger.get();
System.out.println(getAndIncrement); // 输出:1(加1之前的值)
System.out.println(currentValue); // 输出:2(当前值)

2、getAndDecrement

将当前值减1,并返回减1前的值。

AtomicInteger atomicInteger = new AtomicInteger(1);
int getAndDecrement = atomicInteger.getAndDecrement();
int currentValue = atomicInteger.get();
System.out.println(getAndDecrement); // 输出:1(加1之前的值)
System.out.println(currentValue); // 输出:0(当前值)

3、getAndAdd

getAndIncrement 类似,不过 getAndAdd 可以自定义增加一个数值。

AtomicInteger atomicInteger = new AtomicInteger(1);
int getAndAdd = atomicInteger.getAndAdd(10);
int currentValue = atomicInteger.get();
System.out.println(getAndAdd); // 输出:1(加1之前的值)
System.out.println(currentValue); // 输出:11(当前值)

4、incrementAndGet

getAndIncrement 相反,incrementAndGet 是将当前值加1,并返回加1后的值。

AtomicInteger atomicInteger = new AtomicInteger(1);
int incrementAndGet = atomicInteger.incrementAndGet();
int currentValue = atomicInteger.get();
System.out.println(incrementAndGet); // 输出:2(加1之后的值)
System.out.println(currentValue); // 输出:2(当前值)

5、decrementAndGet

getAndDecrement 相反,decrementAndGet 是将当前值减1,并返回减1后的值。

AtomicInteger atomicInteger = new AtomicInteger(1);
int decrementAndGet = atomicInteger.decrementAndGet();
int currentValue = atomicInteger.get();
System.out.println(decrementAndGet); // 输出:0(减1之后的值)
System.out.println(currentValue); // 输出:0(当前值)

6、addAndGet

getAndAdd 相反,addAndGet 是将当前值加上给定的数值,并返回增加后的值。

AtomicInteger atomicInteger = new AtomicInteger(1);
int addAndGet = atomicInteger.addAndGet(10);
int currentValue = atomicInteger.get();
System.out.println(addAndGet); // 输出:11(增加之后的值)
System.out.println(currentValue); // 输出:11(当前值)

7、getAndUpdate

接收一个函数作为参数,通过函数来更新当前值,并且返回更新前的值。源码:

public final int getAndUpdate(IntUnaryOperator updateFunction) {
    int prev, next;
    do {
        prev = get();
        next = updateFunction.applyAsInt(prev);
    } while (!compareAndSet(prev, next));
    return prev;
}

使用示例:

AtomicInteger atomicInteger = new AtomicInteger(1);
int getAndUpdate = atomicInteger.getAndUpdate(e -> e * 100 + 10);
int currentValue = atomicInteger.get();
System.out.println(getAndUpdate); // 输出:1(更新之前的值)
System.out.println(currentValue); // 输出:110(当前值)

8、updateAndGet

接收一个函数作为参数,通过函数来更新当前值,并且返回更新后的值。

示例:

AtomicInteger atomicInteger = new AtomicInteger(1);
int updateAndGet = atomicInteger.updateAndGet(e -> e * 100 + 10);
int currentValue = atomicInteger.get();
System.out.println(updateAndGet); // 输出:110(更新之后的值)
System.out.println(currentValue); // 输出:110(当前值)

9、getAndAccumulate

给定一个数值和一个函数,通过函数对当前值和给定的值进行计算,将计算结果设置为当前值,并返回计算前的值。源码如下:

public final int getAndAccumulate(int x,
                                  IntBinaryOperator accumulatorFunction) {
    int prev, next;
    do {
        prev = get();
        next = accumulatorFunction.applyAsInt(prev, x);
    } while (!compareAndSet(prev, next));
    return prev;
}

示例:

AtomicInteger atomicInteger = new AtomicInteger(4);
int getAndAccumulate = atomicInteger.getAndAccumulate(3, (left, right) -> left * right + 5);
int currentValue = atomicInteger.get();
System.out.println(getAndAccumulate); // 输出:4(计算之后的值)
System.out.println(currentValue); // 输出:17(当前值)

10、accumulateAndGet

给定一个数值和一个函数,通过函数对当前值和给定的值进行计算,将计算结果设置为当前值,并返回计算后的值。

AtomicInteger atomicInteger = new AtomicInteger(4);
int accumulateAndGet = atomicInteger.accumulateAndGet(3, (left, right) -> left * right + 5);
int currentValue = atomicInteger.get();
System.out.println(accumulateAndGet); // 输出:17(计算之后的值)
System.out.println(currentValue); // 输出:17(当前值)

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表