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

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

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

AtomicReferenceArray类的weakCompareAndSetRelease()方法用于将索引 i 处的元素的值自动设置为 newValue,如果当前值等于作为参数传递的预期值,则 AtomicReferenceArray 的 newValue。此方法更新值并确保在此访问后不会重新排序先前的加载和存储。如果为 AtomicRefrence 设置新值成功,则此方法返回 true。

句法:

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

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

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

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

// Java program to demonstrate AtomicReferenceArray
// weakCompareAndSetRelease() 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.00);
        ref.set(1, 123.00);
        ref.set(2, 322.00);
  
        // apply weakCompareAndSetRelease()
        boolean result
            = ref.weakCompareAndSetRelease(
                1,
                124.00,
                234.32);
  
        // print value
        System.out.println("Setting new value"
                           + " is successful = "
                           + result);
  
        System.out.println("Value of index 1 = "
                           + ref.get(1));
    }
}
输出:

方案二:

// Java program to demonstrate AtomicReferenceArray
// weakCompareAndSetRelease() 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, "GFG");
        ref.set(1, "JAVA");
  
        // apply weakCompareAndSetVolatile()
        boolean result
            = ref.weakCompareAndSetVolatile(
                0, "GFG",
                "PYTHON");
  
        // print value
        System.out.println("Setting new value"
                           + " is successful = "
                           + result);
  
        System.out.println("Value of index 0 = "
                           + ref.get(0));
    }
}
输出:

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