AtomicIntegerArray

AtomicIntegerArray 类提供了支持 int 数组的原子更新,还包含高级操作,如变量的读取与写入,保证原子的一致性。

使用示例

两个线程同时对数组对象进行加和减的操作。

public class Test {
    public static void main(String[] args) throws Exception{
        AtomicIntegerArray array = new AtomicIntegerArray(10);
        Thread t1 = new Thread(()->{
            int index;
            for(int i=1; i<100000; i++) {
                index = i%10; //范围0~9
                array.incrementAndGet(index);
            }
        });
        Thread t2 = new Thread(()->{
            int index;
            for(int i=1; i<100000; i++) {
                index = i%10; //范围0~9
                array.decrementAndGet(index);
            }
        });
        t1.start();
        t2.start();
        Thread.sleep(5 * 1000);
        System.out.println(array.toString());
    }
}

结果:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

相关文章: