AtomicReference使用

一、AtomicReference介绍

  • AtomicReferenceAtomicInteger非常类似,不同之处就在于AtomicInteger是对整数的封装,而AtomicReference则对应普通的对象引用。也就是它可以保证你在修改对象引用时的线程安全性

  • AtomicReference是作用是对”对象”进行原子操作。 提供了一种读和写都是原子性的对象引用变量。原子意味着多个线程试图改变同一个AtomicReference(例如比较和交换操作)将不会使得AtomicReference处于不一致的状态。

二、示例


public class AtomicReferenceTest {

    public static void main(String[] args) {
        test4();
    }




    /**
     * 使用 null 初始值创建新的 AtomicReference
     */
    private static void test1() {
        AtomicReference<People> atomicReference = new AtomicReference<>();
        atomicReference.set(new People("张三", 18));
        People people = atomicReference.get();
        System.out.println(people);
    }

    /**
     * 使用给定的初始值创建新的 AtomicReference
     */
    private static void test2() {
        AtomicReference<People> atomicReference = new AtomicReference<>(new People("张三", 18));
        People people = atomicReference.get();
        System.out.println(people);
    }


    /**
     * 如果当前值 == 预期值,则以原子方式将该值设置为给定的更新值。
     */
    private static void test3() {
        People origin = new People("张三", 18);
        AtomicReference<People> atomicReference = new AtomicReference<>(origin);

        //放开该注释,则结果会变
        //atomicReference.set(new People("王五", 25));

        People another = new People("李四", 20);
        boolean result = atomicReference.compareAndSet(origin, another);
        People now = atomicReference.get();
        System.out.println(String.format("set result:%s \nnow:%s", result, now));
    }


    private static void test4() {
        People origin = new People("张三", 18);
        AtomicReference<People> atomicReference = new AtomicReference<>(origin);

        People another = new People("李四", 20);
        People get = atomicReference.getAndSet(another);
        People now = atomicReference.get();
        System.out.println(String.format("get result:%s \nnow:%s", get, now));
    }


    static class People {


        private String name;

        private Integer age;

        public People(String name, Integer age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "People{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值