您的位置:首页 > 其它

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

2016-03-07 15:00 405 查看
通过查看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后的值)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: