4.4.6 数组也能无锁:AtomicIntegerArray
数组也可以实现cas操作,有以下几个类以及用法如下:
public class AtomicTntegerArrayTest { public static void main(String[] args) { AtomicIntegerArray atomicIntegerArray=new AtomicIntegerArray(3); AtomicLongArray atomicIntegerArray1=new AtomicLongArray(3); AtomicReferenceArray atomicReferenceArray=new AtomicReferenceArray(3); //1.获取长度 length System.out.println("方法1"); System.out.println(atomicIntegerArray.length()); //2.将下标i的值设置为 newValue,并且返回旧的值 getAndSet System.out.println("方法2"); System.out.println(atomicIntegerArray.getAndSet(0,1)); System.out.println(atomicIntegerArray.get(0)); //3.进行CAS操作,比较修改compareAndSet System.out.println("方法3"); boolean b = atomicIntegerArray.compareAndSet(0, 1, 2); boolean b1 = atomicIntegerArray.compareAndSet(0, 1, 2); System.out.println(b); System.out.println(b1); //4.将数组的第几个,加1 getAndIncrement,减1 getAndDecrement,返回旧值 System.out.println("方法4"); System.out.println(atomicIntegerArray.getAndIncrement(0));; System.out.println(atomicIntegerArray.get(0)); System.out.println(atomicIntegerArray.getAndDecrement(0)); System.out.println(atomicIntegerArray.get(0)); //5.将第几个元素 加多少addAndGet 返回新值和getAndAdd 返回旧值 System.out.println("方法5"); System.out.println(atomicIntegerArray.get(0)); System.out.println(atomicIntegerArray.addAndGet(0,3)); System.out.println(atomicIntegerArray.get(0)); System.out.println(atomicIntegerArray.getAndAdd(0, 3)); System.out.println(atomicIntegerArray.get(0)); } }
运行结果为:
方法1 3 方法2 0 1 方法3 true false 方法4 2 3 3 2 方法5 2 5 5 5 8