AtomicReference 原子引用

1.简介

赋值操作不是线程安全的。若想不用锁来实现,可以用AtomicReference这个类,实现对象引用的原子更新。

使用场景:一个线程使用student对象,另一个线程负责定时读表,更新这个对象。那么就可以用AtomicReference这个类。

java.util.concurrent.atomic. AtomicReference
类的名字。

2.常用方法

java.util.concurrent.atomic.AtomicReference. AtomicReference(V initialValue)
构造函数。
V java.util.concurrent.atomic.AtomicReference. get()
返回当前的引用。
boolean java.util.concurrent.atomic.AtomicReference. compareAndSet(V expect, V update)

如果当前值与给定的expect相等,(注意是引用相等而不是equals()相等),更新为指定的update值。

V java.util.concurrent.atomic.AtomicReference.getAndSet(V newValue)

原子地设为给定值并返回旧值。

void java.util.concurrent.atomic.AtomicReference.set(V newValue)

注意此方法不是原子的。不明白为什么要提供这个方法,很容易误用。

你可能感兴趣的:(java-并发)