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