Java并发 - AtomicReference类

java.util.concurrent.atomic.AtomicReference类提供可以原子方式读取和写入的底层对象引用的操作,还包含高级原子操作. AtomicReference支持对底层对象引用变量的原子操作.它具有get和set方法,类似于对volatile变量的读写操作.也就是说,一个集合与之前的相关变量的任何后续获取具有先发生关系.原子compareAndSet方法也具有这些内存一致性功能.

AtomicReference方法

以下是AtomicReference类中可用的重要方法列表.

Sr.No.方法&说明
1

public boolean compareAndSet(V expect,V update)

如果当前值==预期值,则以原子方式将值设置为给定的更新值.

2

public boolean get()

返回当前值.

3

public boolean getAndSet(V newValue)

以原子方式设置为给定值并返回先前的值.

4

public void lazySet(V newValue)

最终设置为给定值.

5

public void set(V newValue)

无条件设置为给定值.

6

public String t oString()

返回当前值的String表示.

7

public boolean weakCompareAndSet(V expect,V update)

如果当前值==预期值,则以原子方式将值设置为给定的更新值.

示例

以下TestThread程序显示在基于线程的环境中使用AtomicReference变量.

import java.util.concurrent.atomic.AtomicReference;

public class TestThread {
   private static String message = "hello";
   private static AtomicReference<String> atomicReference;

   public static void main(final String[] arguments) throws InterruptedException {
      atomicReference = new AtomicReference<String>(message);
      
      new Thread("Thread 1") {
         
         public void run() {
            atomicReference.compareAndSet(message, "Thread 1");
            message = message.concat("-Thread 1!");
         };
      }.start();

      System.out.println("Message is: " + message);
      System.out.println("Atomic Reference of Message is: " + atomicReference.get());
   }
}


这将产生以下结果.

输出

Message is: hello
Atomic Reference of Message is: Thread 1