java compareandset 包_Java AtomicReference compareAndSet()用法及代码示例

如果AtomicReference对象的当前值等于期望值,则使用AtomicReference类的compareAndSet()方法以原子方式将newValue的值设置为AtomicReference对象,如果操作成功,则返回true,否则返回false。此方法使用设置的内存语义更新值,就像将该变量声明为volatile一样。

用法:

public final V compareAndSet(V expectedValue,

V newValue)

参数:该方法接受ExpectedValue(期望值)和newValue(新值)来设置新值。

返回值:此方法返回见证值,如果成功,它将与期望值相同。

以下示例程序旨在说明compareAndSet()方法:

程序1:

// Java program to demonstrate

// AtomicReference.compareAndSet() method

import java.util.concurrent.atomic.AtomicReference;

public class GFG {

public static void main(String[] args)

{

// create an atomic reference object.

AtomicReference ref

= new AtomicReference();

// set some value

ref.set(987654321L);

// apply compareAndSet()

boolean response

= ref.compareAndSet(1234L,

999999L);

// print value

System.out.println(" Value is set = "

+ response);

}

}

输出:

Value is set = false

程序2:

// Java program to demonstrate

// AtomicReference.compareAndSet() method

import java.util.concurrent.atomic.AtomicReference;

public class GFG {

public static void main(String[] args)

{

// create an atomic reference object.

AtomicReference ref

= new AtomicReference();

// set some value

ref.set("Geeks For Geeks");

// apply compareAndSet()

boolean response

= ref.compareAndSet(

"Geeks For Geeks",

"GFG");

// print value

System.out.println(" Value is set = "

+ response);

}

}

输出:

Value is set = true

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
AtomicReference.compareAndSetJavaAtomicReference类的一个方法,用于比较当前引用和预期引用是否相等,并在相等的情况下将引用设置为新的值。该方法是原子性操作,可以用于实现多线程环境下的线程安全。 下面是一个示例代码,演示了AtomicReference.compareAndSet用法: ```java import java.util.concurrent.atomic.AtomicReference; public class AtomicReferenceExample { public static void main(String[] args) { AtomicReference<String> atomicReference = new AtomicReference<>("Hello"); // 预期引用为"Hello",当前引用为"Hello",比较相等,设置新的引用为"World" boolean result1 = atomicReference.compareAndSet("Hello", "World"); System.out.println("Result 1: " + result1); // 输出:Result 1: true System.out.println("Current value: " + atomicReference.get()); // 输出:Current value: World // 预期引用为"Hello",当前引用为"World",比较不相等,不修改引用 boolean result2 = atomicReference.compareAndSet("Hello", "Java"); System.out.println("Result 2: " + result2); // 输出:Result 2: false System.out.println("Current value: " + atomicReference.get()); // 输出:Current value: World } } ``` 在这个示例中,我们创建了一个AtomicReference对象,并初始设置为"Hello"。然后我们分别调用compareAndSet方法来尝试修改引用的值。 第一个调用compareAndSet方法时,预期引用为"Hello",当前引用也为"Hello",因此比较相等,设置新的引用为"World"。返回值为true,表示修改成功。最后输出当前引用的值为"World"。 第二个调用compareAndSet方法时,预期引用为"Hello",当前引用已经被修改为"World",不再与预期引用相等,因此不会修改引用的值。返回值为false,表示修改失败。最后输出当前引用的值仍为"World"。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值