📌  相关文章
📜  Java中的 AtomicLongArray compareAndSet() 方法及示例(1)

📅  最后修改于: 2023-12-03 15:16:20.364000             🧑  作者: Mango

Java中的 AtomicLongArray compareAndSet() 方法及示例

在Java中,AtomicLongArray类提供了一种原子方法来操作long类型的数组,其中包括了compareAndSet(int index, long expectedValue, long newValue)方法。这个方法用于比较数组指定位置的值是否等于期望值,并在相等的情况下设置新值。

方法签名
public final boolean compareAndSet(int index, long expectedValue, long newValue)
  • index:要比较和设置的元素的索引位置
  • expectedValue:期望的值
  • newValue:新的值
返回值
  • true:如果成功将数组指定位置的值从期望值更新为新值
  • false:如果期望值与实际值不匹配,则不会更新值
示例

下面是一个示例,展示了如何使用compareAndSet()方法来原子地更新AtomicLongArray对象中指定位置的值。

import java.util.concurrent.atomic.AtomicLongArray;

public class AtomicLongArrayExample {
    public static void main(String[] args) {
        // 创建一个包含5个元素的AtomicLongArray
        AtomicLongArray array = new AtomicLongArray(5);

        // 设置初始值
        for (int i = 0; i < array.length(); i++) {
            array.set(i, i);
        }

        // 将索引为2的元素从2更新为10(期望值为2)
        boolean updated = array.compareAndSet(2, 2, 10);
        if (updated) {
            System.out.println("更新成功");
        } else {
            System.out.println("更新失败");
        }

        // 将索引为2的元素从10更新为20(期望值为2,但实际值为10)
        updated = array.compareAndSet(2, 2, 20);
        if (updated) {
            System.out.println("更新成功");
        } else {
            System.out.println("更新失败");
        }
    }
}

以上示例中,我们首先创建了一个包含5个元素的AtomicLongArray对象,并将初始值设置为从0到4。然后,我们尝试使用compareAndSet()方法将索引为2的元素从2更新为10。由于期望值与实际值匹配,因此更新成功。接着,我们尝试将索引为2的元素从10更新为20,但由于期望值与实际值不匹配,更新失败。

以上的输出结果将会是:

更新成功
更新失败

这个例子展示了compareAndSet()方法的用法,可以用来确保在并发环境中,某个位置上的元素只会被一个线程更新成功。