使用示例
两个线程同时对数组对象进行加和减的操作。
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]