飞翔的小野鸭 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条)

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错