你能解释一下
之间的区别吗?i.compareAndSet(i.get(), i.get() + 1)
和
int s = i.get();
int nextS = s + 1;
i.compareAndSet(s, nextS);
其中i
是AtomicInteger
。如果我想获得i
的增量值,我是对的,第一种方式是错的吗?但我无法解释原因。
答案 0 :(得分:5)
第一种方式是两次调用i.get()
。由于这里没有锁定,这两个调用可能会返回不同的值,这可能与您的预期不同。
答案 1 :(得分:3)
我想获得int的下一个值
那么你可能根本不想要compareAndSet
,你想要updateAndGet
:
updated = i.updateAndGet(value -> value + 1);
或getAndUpdate
如果您想要更新前的值:
previous = i.getAndUpdate(value -> value + 1);