📌  相关文章
📜  Java中的 AtomicReferenceArray weakCompareAndSet() 方法及示例

📅  最后修改于: 2022-05-13 01:55:51.844000             🧑  作者: Mango

Java中的 AtomicReferenceArray weakCompareAndSet() 方法及示例

AtomicReferenceArray类的weakCompareAndSet()方法用于将索引 i 处的元素的值自动设置为 newValue,如果当前值等于作为参数传递的期望值,则 AtomicReferenceArray 的 newValue。此方法使用读取的内存语义更新索引 i 处的值,就好像该变量被声明为 volatile 类型的变量一样。如果为 AtomicReference 设置新值成功,则此方法返回 true。

句法:

public final boolean
       weakCompareAndSet(
           int i, E expectedValue, E newValue)

参数:此方法接受:

  • i是执行操作的 AtomicReferenceArray 的索引,
  • expectedValue是期望值和
  • newValue是要设置的新值。

返回值:如果为 AtomicReference 设置新值成功,则此方法返回true

下面的程序说明了weakCompareAndSet() 方法:
方案一:

// Java program to demonstrate
// weakCompareAndSet() method
  
import java.util.concurrent.atomic.*;
  
public class GFG {
  
    public static void main(String[] args)
    {
  
        // create an atomic reference object.
        AtomicReferenceArray ref
            = new AtomicReferenceArray(5);
  
        // set some value
        ref.set(0, 543);
        ref.set(1, 124);
        ref.set(2, 322);
  
        // apply weakCompareAndSet()
        boolean result
            = ref.weakCompareAndSet(0, 124,
                                    234);
  
        // print value
        System.out.println("Setting new value"
                           + " is successful = "
                           + result);
  
        System.out.println("Value of index 0 = "
                           + ref.get(0));
    }
}
输出:
Setting new value is successful = false
Value of index 0 = 543

方案二:

// Java program to demonstrate
// weakCompareAndSet() method
  
import java.util.concurrent.atomic.*;
  
public class GFG {
  
    public static void main(String[] args)
    {
  
        // create an atomic reference object.c
        AtomicReferenceArray ref
            = new AtomicReferenceArray(5);
  
        // set some value
        ref.set(0, "INDIA");
        ref.set(1, "US");
        ref.set(2, "UK");
        ref.set(3, "CHINA");
        ref.set(4, "CHINA");
  
        // apply weakCompareAndSet()
        boolean result
            = ref.weakCompareAndSet(4, "CHINA",
                                    "CANADA");
  
        // print value
        System.out.println("Setting new value"
                           + " is successful = "
                           + result);
  
        System.out.println("Value of index 4 = "
                           + ref.get(4));
    }
}
输出:
Setting new value is successful = true
Value of index 4 = CANADA

参考: https: Java/util/concurrent/atomic/AtomicReferenceArray.html#weakCompareAndSet(V, V)