有什么不同?

时间:2016-07-02 09:46:58

标签: java multithreading atomic

你能解释一下

之间的区别吗?
i.compareAndSet(i.get(), i.get() + 1)

int s = i.get();
int nextS = s + 1;
i.compareAndSet(s, nextS);

其中iAtomicInteger。如果我想获得i的增量值,我是对的,第一种方式是错的吗?但我无法解释原因。

2 个答案:

答案 0 :(得分:5)

第一种方式是两次调用i.get()。由于这里没有锁定,这两个调用可能会返回不同的值,这可能与您的预期不同。

答案 1 :(得分:3)

  

我想获得int的下一个值

那么你可能根本不想要compareAndSet,你想要updateAndGet

updated = i.updateAndGet(value -> value + 1);

getAndUpdate如果您想要更新前的值:

previous = i.getAndUpdate(value -> value + 1);