多线程- Atomic 中的 incrementAndGet与 getAndIncrement 两个方法的区别

版权声明:中华人民共和国持有版权 https://blog.csdn.net/Fly_Fly_Zhang/article/details/89421118

int incrementAndGet()

以原子方式将当前值加 1。

int getAndIncrement()

以原子方式将当前值加 1。

再进行源代码查看:

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

由此可以看出,两个方法处理的方式都是一样的,区别在于

getAndIncrement方法是返回旧值(即加1前的原始值)
incrementAndGet返回的是新值(即加1后的值)

猜你喜欢

转载自blog.csdn.net/Fly_Fly_Zhang/article/details/89421118