java.util.concurrent.atomic.AtomicIntegerArray类提供可以原子方式读取和写入的基础int数组的操作,还包含高级原子操作. AtomicIntegerArray支持对底层int数组变量的原子操作.它具有get和set方法,类似于对volatile变量的读写操作.也就是说,一个集合与之前的相关变量的任何后续获取具有先发生关系.原子compareAndSet方法也具有这些内存一致性功能.
AtomicIntegerArray方法
以下是AtomicIntegerArray类中可用的重要方法列表.
Sr.No. | 方法&说明 |
---|---|
1 | public int addAndGet(int i,int delta) 以原子方式将给定值添加到索引i处的元素. |
2 | public boolean compareAndSet(int i ,int expect,int update) 如果当前值==期望值,则以原子方式将位置i的元素设置为给定的更新值. |
3 | public int decrementAndGet(int i) 原子地将索引i处的元素减1. |
4 | public int get(int i) 获取位置i的当前值. |
5 | public int getAndAdd(int i,int delta) 以原子方式将给定值添加到索引i处的元素. |
6 | public int getAndDecrement (int i) 原子地将索引i处的元素减1. |
7 | public int getAndIncrement(int i) 以原子方式将索引为i的元素加1. |
8 | public int getAndSet(int i,int newValue) 以原子方式将位置i的元素设置为给定值并返回旧值. |
9 | public int incrementAndGet(int i) 以原子方式递增1索引i的元素. |
10 | public void lazySet(int i,int newValue) 最终将位置i的元素设置为给定值. |
11 | public int length() 返回数组的长度. |
12 | public void set(int i,int newValue) 将位置i的元素设置为给定值. |
13 | public String toString() 返回数组当前值的String表示. |
14 | public boolean weakCompareAndSet(int i,int expect,int update) 如果当前值==预期值,则以原子方式将位置i的元素设置为给定的更新值. |
示例
以下TestThread程序显示在基于线程的环境中使用AtomicIntegerArray变量.
import java.util.concurrent.atomic.AtomicIntegerArray;public class TestThread { private static AtomicIntegerArray atomicIntegerArray = new AtomicIntegerArray(10); public static void main(final String[] arguments) throws InterruptedException { for (int i = 0; i这将产生以下结果.
输出
Thread 10, index 0, value: 2Thread 10, index 1, value: 2Thread 10, index 2, value: 2Thread 11, index 0, value: 3Thread 10, index 3, value: 2Thread 11, index 1, value: 3Thread 11, index 2, value: 3Thread 10, index 4, value: 2Thread 11, index 3, value: 3Thread 10, index 5, value: 2Thread 10, index 6, value: 2Thread 11, index 4, value: 3Thread 10, index 7, value: 2Thread 11, index 5, value: 3Thread 10, index 8, value: 2Thread 11, index 6, value: 3Thread 10, index 9, value: 2Thread 11, index 7, value: 3Thread 11, index 8, value: 3Thread 11, index 9, value: 3Values:3 3 3 3 3 3 3 3 3 3