AtomicLong类在高并发的场景下使用比较多,下面列举一下这个类中经常使用到的方法:
AtomicLong aLong = new AtomicLong(1);
System.out.println(aLong.get());
System.out.println(aLong);
// 初始化一个值
AtomicLong val = new AtomicLong(0);
//将val变量增加1
long res = val.getAndIncrement();
//将val变量加1之前的值打印出来
System.out.println("Previous value: " + res);
//将val加1之后的值打印出来
System.out.println("Current value: " + val);
//将val变量加1之前的值打印出来
System.out.println("Previous value: " + res);
运行结果:
1
1
Previous value: 0
Current value: 1
Previous value: 0