• 小小Javaer没用过AtomicInteger?


    Class

    1. java.lang.Object
    2. java.lang.Number
    3. java.util.concurrent.atomic.AtomicInteger
    4. 实现的接口:Serializable

     

    注意(官方翻译):
    AtomicInteger 在Java 1.5就已经存在了,该类不是 java.lang.Integer 的替代品!该类中并没有自定义equalshashCodecompareTo等方法。 因为原子变量预计会发生变异,所以它们是哈希表键的糟糕选择。

    使用场景介绍:

    1. 多线程情况下我们对int值执行原子操作(即用作原子计数器),而无需使用Synchronized关键字。
    2. 多线程情况下对int值的赋值操作 :compareAndSet

    构造函数

    构造函数描述
    AtomicInteger()创建一个具有初始值为0的 AtomicInteger
    AtomicInteger(int initialValue)使用给定的初始值创建一个新的 AtomicInteger

    原子计数

    方法介绍:

    方法修饰符、返回类型方法名描述
    final intget()返回当前值
    intintValue()以int形式返回当前值,底层就是调用的get()
    final intaddAndGet()以原子方式将给定值添加到当前值,并在添加后返回新值
    final intgetAndAdd以原子方式将给定值添加到当前值并返回旧值
    final intcrementAndGet以原子方式将当前值增加1,并在增加之后返回新值。 它等效于++i 操作
    final intgetAndIncrement以原子方式递增当前值并返回旧值。 它等效于i ++操作
    final intdecrementAndGet以原子方式将当前值减1,并在减后返回新值。 它等效于 i-- 操作
    final intgetAndDecrement以原子方式减少当前值并返回旧值。 它等效于 --i操作

    demo:


     

    1. public static void main(String[] args) {
    2. AtomicInteger atomicInteger = new AtomicInteger(10);
    3. System.out.println(atomicInteger.get()); //10
    4. System.out.println(atomicInteger.intValue()); //10
    5. System.out.println(atomicInteger.addAndGet(1)); //11
    6. System.out.println(atomicInteger); //11
    7. System.out.println(atomicInteger.getAndAdd(1)); //11
    8. System.out.println(atomicInteger); //12
    9. System.out.println(atomicInteger.incrementAndGet()); //13
    10. System.out.println(atomicInteger); //13
    11. System.out.println(atomicInteger.getAndIncrement()); //13
    12. System.out.println(atomicInteger); //14
    13. System.out.println(atomicInteger.decrementAndGet()); //13
    14. System.out.println(atomicInteger); //13
    15. System.out.println(atomicInteger.getAndDecrement()); //13
    16. System.out.println(atomicInteger); //12
    17. }

    compareAndSet

    方法介绍:

    方法修饰符、返回类型方法名描述
    final booleancompareAndSet(int expectedValue, int newValue)如果当前值等于预期值,以原子方式将值设置为newValue,修改成功返回true,否则false

    compareAndSet方法实际上是做了两步操作:

    • 第一步是比较当前value值是否为预期值(expectedValue)
    • 第二步是把当前value值更新为newValue,这两步是原子操作,在没有多线程锁的情况下,借助cpu锁保证数据安全。

    demo:


     

    1. public static void main(String[] args) {
    2. AtomicInteger atomicInteger = new AtomicInteger(10);
    3. System.out.println(atomicInteger.compareAndSet(10,20)); //true
    4. System.out.println(atomicInteger.compareAndSet(10,20)); //false
    5. }

  • 相关阅读:
    TableView (cocos-2dx lua)
    最全ROS 入门
    js 将多张图片合并成一张图片
    Radis缓存异常以及处理方案(雪崩击穿穿透预热降级)
    [附源码]计算机毕业设计JAVAjsp宾馆客房管理系统
    JavaScript高级技巧:深入探索JavaScript语言的高级特性和用法
    【MQ基本概念 MQ的工作原理】
    edu 156 div2 c
    关于代码混淆,看这篇就够了
    带你解密Linux的【Vm】
  • 原文地址:https://blog.csdn.net/m0_73088370/article/details/126747699