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

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

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

AtomicReferenceArray类的weakCompareAndSetAcquire()方法用于将索引 i 处的元素的值自动设置为 newValue,如果当前值等于作为参数传递的预期值,则 AtomicReferenceArray 的 newValue。此方法使用与 memory_order_acquire 排序兼容的内存排序效果更新索引 i 处的值。如果为 AtomicRefrence 设置新值成功,则此方法返回 true。

句法:

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

参数:此方法接受:

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

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

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

// Java program to demonstrate
// weakCompareAndSetAcquire() 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, 123);
        ref.set(2, 5443);
  
        // apply weakCompareAndSetAcquire()
        boolean result
            = ref.weakCompareAndSetAcquire(
                0,
                5443,
                234);
  
        // print value
        System.out.println(
            "Setting new value"
            + " is successful = "
            + result);
  
        System.out.println("Value of index 0 = "
                           + ref.get(0));
    }
}
输出:

方案二:

// Java program to demonstrate
// weakCompareAndSetAcquire() method
  
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, "PYTHON");
        ref.set(2, "TS");
        ref.set(3, "C++");
        ref.set(4, "C");
  
        // apply weakCompareAndSetAcquire()
        boolean result
            = ref.weakCompareAndSetAcquire(
                4,
                "C",
                "JAVA");
  
        // 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#weakCompareAndSetAcquire(V, V)