飞翔的小野鸭 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 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?