通过查看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后的值)