通过查看JDK的API知道:
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后的值)

本文详细解析了JDK中Atomic类的incrementAndGet与getAndIncrement方法的区别。这两种方法虽然都是以原子方式增加当前值,但前者返回增加后的值,后者则返回增加前的值。
2525

被折叠的 条评论
为什么被折叠?



