本篇文章的主要内容如下:
1:AtomicIntegerArray实例
2:AtomicIntegerArray的源码解析
3:AtomicInLongArray
1、AtomicIntegerArray实例
接下来的例子是定义一个普通的整型数组和一个AtomicIntegerArray在多线程下添加元素,看看会出现什么效果。
public class AtomicIntegerArrayTest {
private static int[] intArr = new int[5];
private static AtomicIntegerArray aiArr = new AtomicIntegerArray(5);
private static ThreadPoolExecutor pool;
static {
pool = new ThreadPoolExecutor(5, 10, 1, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1000));
}
public static void main(String[] args) throws InterruptedException {
intArrTest();
aiArrTest();
pool.awaitTermination(3, TimeUnit.SECONDS);
System.out.println(“AtomicInteger=” + aiArr);
StringBuilder sb = new StringBuilder(“整形数组=[”);
for(int i=0;i<intArr.length;i++){
sb.append(intArr[i]).append(" “);
}
sb.append(”]");
System.out.println(sb.toString());
pool.shutdown();
}
//普通整型数组多线程下添加元素
public static void intArrTest() {
for (int i = 0; i < 5; i++) {
pool.execute(() -> {
for (int j = 0; j < 10000; j++) {
intArr[j % 5]++;
}
});
}
}
//AtomicIntegerArray多线程下添加元素
public static void aiArrTest() {
for (int i = 0; i < 5; i++) {
pool.execute(() -> {
for (int j = 0; j < 10000; j++) {
aiArr.getAndIncrement(j % 5);
}
});
}
}
}
运行结果如下:
Java并发包-atomic包-让您彻底掌握AtomicIntegerArray源码
Java并发包-atomic包-让您彻底掌握AtomicIntegerArray源码
通过上面的运行结果可以看出,普通的int[]数组每一次运行结果都是不同的,而AtomicIntegerArray无论运行多少次,运行结果都是一样且正确的。所以大家是不是明白了AtomicIntegerArray是保证数组中元素的原子操作,而不是数组本身的原子操作。
2、AtomicIntegerArray的源码解析
首先