本文演示原子数组的使用方法,我们使用100自增线程和100自减线程对AtomicIntegerArray进行自增和自减操作,核对最终的结果是否为零。
实例代码
实例代码如下,最终结果为零。
package com.yang.atomic; import java.util.concurrent.atomic.AtomicIntegerArray; /** * 本实例演示原子数组 */ public class AtomicIntegerArrayDemo { private static AtomicIntegerArray atomicIntegerArray = new AtomicIntegerArray(100); public static void main(String[] args) throws InterruptedException { Increment incrementRunnable=new Increment(atomicIntegerArray); Decrement decrementRunnbale=new Decrement(atomicIntegerArray); Thread[] incrementThreads=new Thread[100]; Thread[] decrementThreads=new Thread[100]; for (int i = 0; i < 100; i++) { incrementThreads[i]=new Thread(incrementRunnable); decrementThreads[i]=new Thread(decrementRunnbale); incrementThreads[i].start(); decrementThreads[i].start(); } for (int i = 0; i < 100; i++) { incrementThreads[i].join(); decrementThreads[i].join(); } for (int i = 0; i < 100; i++) { System.out.println(atomicIntegerArray.get(i)); } System.out.println("运行结束"); } } class Increment implements Runnable { private AtomicIntegerArray array; public Increment(AtomicIntegerArray array) { this.array = array; } @Override public void run() { for (int i = 0; i < 100; i++) { array.getAndIncrement(i); } } } class Decrement implements Runnable { private AtomicIntegerArray array; public Decrement(AtomicIntegerArray array) { this.array = array; } @Override public void run() { for (int i = 0; i < 100; i++) { array.getAndDecrement(i); } } }