public final int getAndIncrement() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return current;
}
}
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
书上说:
源码中for循环体的第一步先取得AtomicInteger里存储的数值,第二步对AtomicInteger的当前数值进行加1操作,关键的第三步调用compareAndSet方法来进行原子更新操作,该操作先检查当前数值是否等于current,等于意味着AtomicInteger的值没有被其他线程修改过,则将AtomicInteger的当前数值更新成next的值,如果不等compareAndSet方法会返回false,程序会进入for循环重新进行compareAndSet操作。
我的疑问:
如果已经被其他线程修改过,此时再执行for()循环有什么意义呢?预期将3变成4,可谁知这时候被其他线程改成5了,不满足compareAndSet,此时重新进去for()循环又能怎么样呢?费解
http://blog.csdn.net/zhangerqing/article/details/43057799
已经那么久的问题了 我说说我的理解吧,楼主的疑问其实就在于对current的值理解偏差了,current的值一定是atomicinteger对象最新的值
,所以如果在compareAndSet时其它线程改变了AtomicInteger的值,那么下一次循环的时候current的值就是其它线程改变后的值。接着再拿
这个改变后的值做compareAndSet操作。