目录

并发 - AtomicReference( AtomicReference)

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

原子参考方法

以下是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 toString()

返回当前值的String表示形式。

7

public boolean weakCompareAndSet(V expect, V update)

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

例子 (Example)

以下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());
   }
}

这将产生以下结果。

输出 (Output)

Message is: hello
Atomic Reference of Message is: Thread 1
↑回到顶部↑
WIKI教程 @2018