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

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

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

AtomicReferenceArray类的weakCompareAndSetPlain()方法用于将索引 i 处的元素的值自动设置为 newValue,如果当前值等于作为参数传递的预期值,则 AtomicReferenceArray 的 newValue。此方法使用设置的内存语义更新索引 i 处的值,就好像索引 i 处的变量被声明为非易失性和非最终的。如果设置新值成功,则此方法返回 true。

句法:

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

参数:此方法接受i ,它是 AtomicReferenceArray 的索引来执行操作, expectedValue是期望值, newValue是要设置的新值。

返回值:如果成功,此方法返回true。

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

// Java program to demonstrate AtomicReferenceArray
// weakCompareAndSetPlain() method
  
import java.util.concurrent.atomic.AtomicReferenceArray;
  
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, 321);
        ref.set(1, 123);
        ref.set(2, 322);
  
        // apply weakCompareAndSetPlain()
        boolean result
            = ref.weakCompareAndSetPlain(
                0, 124,
                234);
  
        // print value
        System.out.println("Setting new value"
                           + " is successful = "
                           + result);
  
        System.out.println("Value of index 0 = "
                           + ref.get(1));
    }
}
输出:

方案二:

// Java program to demonstrate AtomicReferenceArray
// weakCompareAndSetPlain() method
  
import java.util.concurrent.atomic.AtomicReferenceArray;
  
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, "C");
        ref.set(1, "JAVA");
        ref.set(2, "JS");
        ref.set(3, "C++");
        ref.set(4, "C");
  
        // apply weakCompareAndSetVolatile()
        boolean result
            = ref.weakCompareAndSetVolatile(
                4, "C",
                "PYTHON");
  
        // print value
        System.out.println("Setting new value"
                           + " is successful = "
                           + result);
  
        System.out.println("Value of index 4 = "
                           + ref.get(4));
    }
}
输出:

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