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

    用法:

    1. public final V compareAndSet(V expectedValue,V newValue)
    2. 参数:该方法接受ExpectedValue(期望值)和newValue(新值)来设置新值。
    3. 返回值:此方法返回见证值,如果成功,它将与期望值相同。

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

    1. // Java program to demonstrate
    2. // AtomicReference.compareAndSet() method
    3. import java.util.concurrent.atomic.AtomicReference;
    4. public class GFG {
    5. public static void main(String[] args)
    6. {
    7. // create an atomic reference object.
    8. AtomicReference<Long> ref = new AtomicReference<Long>();
    9. // set some value
    10. ref.set(987654321L);
    11. // apply compareAndSet()
    12. boolean response
    13. = ref.compareAndSet(1234L,
    14. 999999L);
    15. // print value
    16. System.out.println(" Value is set = "
    17. + response);
    18. }
    19. }

    输出:

    1. Value is set = false


    程序2:

    1. // Java program to demonstrate
    2. // AtomicReference.compareAndSet() method
    3. import java.util.concurrent.atomic.AtomicReference;
    4. public class GFG {
    5. public static void main(String[] args)
    6. {
    7. // create an atomic reference object.
    8. AtomicReference<String> ref
    9. = new AtomicReference<String>();
    10. // set some value
    11. ref.set("Geeks For Geeks");
    12. // apply compareAndSet()
    13. boolean response
    14. = ref.compareAndSet(
    15. "Geeks For Geeks",
    16. "GFG");
    17. // print value
    18. System.out.println(" Value is set = "
    19. + response);
    20. }
    21. }


    输出:

    1. Value is set = true