public static void main(String[] args) throws Exception {
// agree();
//1、创建默认值为0
AtomicLong atomicLong = new AtomicLong();
System.out.println("默认值为0:" + atomicLong.get());
//2、创建值为10的 AtomicLong
AtomicLong atomicLong1 = new AtomicLong(10);
System.out.println("创建值为10的AtomicLong:" + atomicLong1.get());
//3、以原子方式先将 3+5,再获取值为8
AtomicLong atomicLong2 = new AtomicLong(3);
atomicLong2.addAndGet(5);
System.out.println("以原子方式先将 3+5,再获取值为8:" + atomicLong2.get());
//4、以普通方式 先获取 10 ,再10+5 (不会保证原子性)
AtomicLong atomicLong3 = new AtomicLong(10);
atomicLong3.getAndAdd(5);
System.out.println("以普通方式 先获取 10 ,再10+5 (不会保证原子性):" + atomicLong3.get());
//5、以原子方式比较 如果 atomicLong4的值为10,将值改为15
AtomicLong atomicLong4 = new AtomicLong(10);
atomicLong4.compareAndSet(10,15);
System.out.println("以原子方式比较 如果 atomicLong4的值为10,将值改为15:" + atomicLong4.get());
//6、 以原子方式将先减 1,再获取值
AtomicLong atomicLong5 = new AtomicLong(10);
atomicLong5.decrementAndGet();
System.out.println("以原子方式将先减 1,再获取值:" + atomicLong5.get());
//7、普通方式先获取当前值再减1 (不会保证原子性)
AtomicLong atomicLong6 = new AtomicLong();
atomicLong6.getAndDecrement();
System.out.println("普通方式先获取当前值再减1 (不会保证原子性):" + atomicLong6.get());
//8、普通方式先获取当前值再加1 (不会保证原子性)
AtomicLong atomicLong7 = new AtomicLong();
atomicLong7.getAndIncrement();
System.out.println("普通方式先获取当前值再加1 (不会保证原子性):" + atomicLong7.get());
//9、以原子方式先加1再获取当前值
AtomicLong atomicLong8 = new AtomicLong();
atomicLong8.incrementAndGet();
System.out.println("以原子方式先加1再获取当前值:" + atomicLong8.get());
//10、普通方式先获取当前值再设置新的值 (不会保证原子性)
AtomicLong atomicLong9 = new AtomicLong();
atomicLong9.getAndSet(20);
System.out.println("普通方式先获取当前值再设置新的值 (不会保证原子性):" + atomicLong9.get());
}
结果