AtomicReference详解
  Olt1rl96HKat 2023年11月22日 20 0

AtomicReference是Java中的一个原子引用类型,位于java.util.concurrent.atomic包下。它提供了原子性地更新和访问引用对象的操作。

AtomicReference的主要特点如下:

1.原子性:AtomicReference提供了一些原子方法,可以在多线程环境下原子性地操作引用对象。

2.线程安全:由于AtomicReference的操作是原子性的,它可以确保在并发环境中正确处理引用对象的读取和更新,避免了竞态条件。

3.引用对象的原子性操作:AtomicReference的原子方法如get、set、compareAndSet等,针对引用对象进行操作,而不是对象内部的属性或字段。

以下是AtomicReference的一些常用方法:

get():获取当前引用对象的值。

set(T newValue):设置新的引用对象的值。

compareAndSet(T expect,T updated):如果当前引用对象的值等于expect,则将其更新为update。

getAndSet(T newValue):设置新的引用对象的值,并返回旧的引用对象的值。

import java.util.concurrent.atomic.AtomicReference;

public class Main {
    public static void main(String[] args) {
        AtomicReference<String> atomicRef = new AtomicReference<>("Hello");
 
        String oldValue = atomicRef.get();
        System.out.println("oldValue: " + oldValue);
 
        atomicRef.set("World");
 
        String updatedValue = atomicRef.get();
        System.out.println("updatedValue: " + updatedValue);
 
        boolean exchanged = atomicRef.compareAndSet("world", "Hello");
        System.out.println("exchanged: " + exchanged);
 
        String finalValue = atomicRef.get();
        System.out.println("finalValue: " + finalValue);
    }
}

输出结果

oldValue: Hello
updatedValue: World
exchangedt: false
finalValue: World
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月22日 0

暂无评论

推荐阅读
Olt1rl96HKat
作者其他文章 更多

2023-12-22

2023-12-22

2023-12-15

2023-12-15

2023-12-15

2023-12-15

2023-12-15