飞翔的小野鸭 2018-08-09 09:55 采纳率: 34.9%
浏览 2313
已采纳

Java AtomicReference 中 compareAndSet的更新问题

private static AtomicReference<Integer> atomicReference = new AtomicReference<>(0);

    private static AtomicReference<Integer> atomicReference1 = new AtomicReference<>(100);

 atomicReference.compareAndSet(0, 2);
        atomicReference.compareAndSet(0, 3);
        atomicReference.compareAndSet(2, 4);
        atomicReference.compareAndSet(3, 5);
        System.out.println(atomicReference.get());


        atomicReference1.compareAndSet(100, 200);
        atomicReference1.compareAndSet(100, 300);
        atomicReference1.compareAndSet(200, 400);
        atomicReference1.compareAndSet(300, 500);
        System.out.println(atomicReference1.get());

然而运行出来的结果
atomicReference为4
atomicReference1为200.

问题.atomicReference1为什么是200 而不是400

  • 写回答

2条回答

  • _zming 2018-08-09 10:53
    关注

    首先compareAndSet使用==比较,看注释:
    Atomically sets the value to the given updated value
    * if the current value {@code ==} the expected value.

        其次为什么128以内的整数可以而超过128不可以?
        对于int字面量java会进行装箱将其转换成Integer对象,调用的是Integer.valueOf方法,
        看源码你就明白了,128以内的会使用缓存,同一个int字面量返回同一个对象用==比较为true,而超过128返回不是同一个对象,==为false,equal才是true:
        public static Integer valueOf(int i) {
        if(i >= -128 && i <= IntegerCache.high)
            return IntegerCache.cache[i + 128];
        else
            return new Integer(i);
    }
        祝你好运!
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧