在开发 AtomicInteger 时,我发现这个 API 提供了两种方法。
比较和交换:
Atomically sets the value to newValue if the current value, referred to as the witness value, == expectedValue, with memory effects as specified by
VarHandle.compareAndExchange(java.lang.Object...)
比较并设置:
Atomically sets the value to
newValue
if the currentvalue == expectedValue
, with memory effects as specified byVarHandle.compareAndSet(java.lang.Object...)
.
我无法理解两者之间的区别,请帮助提供合适的示例。
最佳答案
这两个方法有不同的返回类型。
compareAndSet
返回 boolean
:
true if successful. False return indicates that the actual value was not equal to the expected value.
compareAndExchange
返回一个 int
:
the witness value, which will be the same as the expected value if successful
即compareAndSet
指示变量的值是否已更新,而 compareAndExchange
返回变量的当前值,从而为您提供更多信息。
1
,compareAndSet(1,2)
会将原子整数的值设置为 2
,并返回在这种情况下,true
。否则,它将不会设置该值,并且将返回false
。
1
,compareAndExchange(1,2)
会将原子整数的值设置为 2
,并且将在这种情况下返回1
。如果先前的值不是 1
,则不会设置该值,并返回当前(未更改的)值。
关于java - 原子整数的compareandexchange()与compareandset(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60648557/