java——AtomicInteger 中 incrementAndGet与getAndIncrement 两个方法的区别

时间:2024-10-19 17:04:08

https://blog.****.net/chenkaibsw/article/details/81031950

源码:

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

通过代码可以看出:

getAndIncrement返回的是当前值;
incrementAndGet返回的是加1后的值。