📅  最后修改于: 2020-11-15 03:54:55             🧑  作者: Mango
java.util.concurrent.atomic.AtomicReference类提供了对基础对象引用的操作,这些操作可以原子方式读写,并且还包含高级原子操作。 AtomicReference支持对基础对象引用变量的原子操作。它具有get和set方法,它们的工作方式类似于对易失性变量的读写。也就是说,一个集合与该变量的任何后续get都具有事前发生的关系。原子compareAndSet方法还具有这些内存一致性功能。
以下是AtomicReference类中可用的重要方法的列表。
Sr.No. | Method & Description |
---|---|
1 |
public boolean compareAndSet(V expect, V update) Atomically sets the value to the given updated value if the current value == the expected value. |
2 |
public boolean get() Returns the current value. |
3 |
public boolean getAndSet(V newValue) Atomically sets to the given value and returns the previous value. |
4 |
public void lazySet(V newValue) Eventually sets to the given value. |
5 |
public void set(V newValue) Unconditionally sets to the given value. |
6 |
public StringtoString() Returns the String representation of the current value. |
7 |
public boolean weakCompareAndSet(V expect, V update) Atomically sets the value to the given updated value if the current value == the expected value. |
以下TestThread程序显示了在基于线程的环境中AtomicReference变量的用法。
import java.util.concurrent.atomic.AtomicReference;
public class TestThread {
private static String message = "hello";
private static AtomicReference atomicReference;
public static void main(final String[] arguments) throws InterruptedException {
atomicReference = new AtomicReference(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