AtomicBoolean 中 getAndSet 和 compareAndSet 的区别 [英] Difference between getAndSet and compareAndSet in AtomicBoolean
问题描述
线程标题应该是不言自明的......我对 AtomicBoolean
类的以下方法的规范有点困惑:
The thread title should be self-explnatory... I'm a bit confused between the specification of below methos from AtomicBoolean
class:
java.util.concurrent.atomic.AtomicBoolean#compareAndSet
java.util.concurrent.atomic.AtomicBoolean#getAndSet
我的看法是,当在 if
条件中用作布尔子句时,两者都会导致相同的行为:
My assemption is that both would result in the same behavior when used as a boolean clause in an if
condition:
public class Test {
private AtomicBoolean flag = AtomicBoolean(false);
public void processSomeAction() {
if (flag.getAndSet(false)) { // Shouldn't this be similar to flag.compareAndSet(false)
// process some action
}
}
//...
private void internalMutatorMethod() {
// do some staff then update the atomic flag
flas.set(true);
}
}
假设我想检索当前标志值并自动更新它,这两种方法不应该产生相同的行为吗?
Assuming that I want to retrieve the current flag value and update it automaticlly, shouldn't both methods produce the same behavior?
如果我遗漏了内部差异,我将非常感谢有关如何以及何时使用每一个的解释.
I would much appreciate any explanations regarding how and when to use each of those if I'm missing internal differences.
推荐答案
文档 非常清楚.
getAndSet
--> 原子地设置为给定值并返回前一个值."compareAndSet
--> 如果当前值 == 预期值,则原子地将值设置为给定的更新值."
getAndSet
--> "Atomically sets to the given value and returns the previous value."compareAndSet
--> "Atomically sets the value to the given updated value if the current value == the expected value."
毫不奇怪,compareAndSet
需要两个参数.
Not surprisingly, compareAndSet
takes two arguments.
在您的具体情况下:
if (flag.getAndSet(false))
只会在flag
之前的值为true
时将其设置为false
代码>- 这相当于
if (flag.compareAndSet(true, false))
if (flag.getAndSet(false))
will setflag
tofalse
only if its previous value wastrue
- That would be the equivalent of
if (flag.compareAndSet(true, false))
这篇关于AtomicBoolean 中 getAndSet 和 compareAndSet 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!