本文介绍了Java原子变量set()vs compareAndSet()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道原子类中的set()和compareAndSet()之间的区别. set()方法还可以确保原子过程吗?例如下面的代码:

I want to know the difference between set() and compareAndSet() in atomic classes. Does the set() method also ensure the atomic process? For example this code:

public class sampleAtomic{
    private static AtomicLong id = new AtomicLong(0);

    public void setWithSet(long newValue){
        id.set(newValue);
    }

    public void setWithCompareAndSet(long newValue){
        long oldVal;
        do{
            oldVal = id.get();
        }
        while(!id.compareAndGet(oldVal,newValue)
    }
}

这两种方法是否相同?

推荐答案

setcompareAndSet方法的行为不同:

  • compareAndSet:如果当前值等于(==)与期望值,则以原子方式将该值设置为给定的更新值.
  • set:设置为给定值.

是的.这是原子的.因为只有一个操作涉及到set新值.下面是set方法的源代码:

Yes. It is atomic. Because there is only one operation involved to set the new value. Below is the source code of the set method:

public final void set(long newValue) {
        value = newValue;
}

这篇关于Java原子变量set()vs compareAndSet()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 00:21