AtomicBoolean中getAndSet和compareAndSet之间的区别 [英] Difference between getAndSet and compareAndSet in AtomicBoolean

查看:1705
本文介绍了AtomicBoolean中getAndSet和compareAndSet之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

主题标题应该是自我探索的...我在 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

  • 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 设置为 false 仅当前一个值为<$ c时$ c> true

  • 这相当于 if(flag.compareAndSet(true,false))

  • if (flag.getAndSet(false)) will set flag to false only if its previous value was true
  • That would be the equivalent of if (flag.compareAndSet(true, false))

这篇关于AtomicBoolean中getAndSet和compareAndSet之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆