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

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

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

在Java中,AtomicIntegerArray是一个原子类,它提供了对表示整数的数组进行原子操作的支持,包括读、写和更新操作。其中,compareAndSet()方法是其中的一种CAS(Compare And Swap)操作,它在多线程环境下可以保证原子性。

方法介绍

compareAndSet(int i, int expect, int update)方法是AtomicIntegerArray类中的一个实例方法,它的作用是将数组中索引为i的值与期望值expect比较,如果相等,则将其更新为update,并返回true,否则不进行更新,返回false

方法的具体参数含义如下:

  • i:要进行操作的数组索引
  • expect:期望值
  • update:更新值
示例

下面是一个利用AtomicIntegerArraycompareAndSet()方法实现的多线程操作示例:

import java.util.concurrent.atomic.AtomicIntegerArray;

public class AtomicIntegerArrayExample {
    private static AtomicIntegerArray array = new AtomicIntegerArray(new int[]{0, 1, 2});

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new IncrementTask());
        Thread t2 = new Thread(new DecrementTask());
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("Final array: ");
        for (int i = 0; i < array.length(); i++) {
            System.out.println(array.get(i));
        }
    }

    static class IncrementTask implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < array.length(); i++) {
                int oldValue, newValue;
                do {
                    oldValue = array.get(i);
                    newValue = oldValue + 1;
                } while (!array.compareAndSet(i, oldValue, newValue));
            }
        }
    }

    static class DecrementTask implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < array.length(); i++) {
                int oldValue, newValue;
                do {
                    oldValue = array.get(i);
                    newValue = oldValue - 1;
                } while (!array.compareAndSet(i, oldValue, newValue));
            }
        }
    }
}

该示例中,定义了一个AtomicIntegerArray类型的数组array,并初始化为{0, 1, 2}。同时,定义了两个线程IncrementTaskDecrementTask,分别用于对数组进行加一和减一操作。在每个线程中,使用do-while循环进行compareAndSet()操作,直到数组值被成功更新。最后,输出操作后的数组结果。

在运行该示例程序后,输出结果如下:

Final array: 
1
0
1

以上示例说明了AtomicIntegerArray compareAndSet()方法的使用,并且说明了其在多线程环境下可以保证操作的原子性。