写在前面:
AtomicReference类提供了一个可以原子读写的对象引用变量。 原子意味着尝试更改相同AtomicReference的多个线程(例如,使用比较和交换操作)不会使AtomicReference最终达到不一致的状态。 AtomicReference甚至有一个先进的compareAndSet(object expect. object update)方法,它可以将引用与预期值(引用)进行比较,如果它们相等,则在AtomicReference对象内设置一个新的引用。
创建一个AtomicReference:
AtomicReference atomicReference = new AtomicReference();
String initialReference = "the initially referenced string";
AtomicReference atomicReference = new AtomicReference(initialReference);
创建一个类型的AtomicReference:
AtomicReference<String> atomicStringReference = new AtomicReference<String>();
获取值:
AtomicReference atomicReference = new AtomicReference("first value referenced");
String reference = (String) atomicReference.get();
赋值:
AtomicReference atomicReference =
new AtomicReference();
atomicReference.set("New object referenced");
比较赋值:
String initialReference = "initial value referenced";
AtomicReference<String> atomicStringReference =
new AtomicReference<String>(initialReference);
System.out.println(atomicStringReference.get()); //initial value referenced
String newReference = "new value referenced";
// 预期值(第一个)与已存在内存值比较,如果相等则更新为第二个
boolean exchanged = atomicStringReference.compareAndSet(initialReference, newReference);
System.out.println("exchanged: " + exchanged); //true,
System.out.println(atomicStringReference.get()); //new value referenced
exchanged = atomicStringReference.compareAndSet(initialReference, newReference);
System.out.println("exchanged: " + exchanged); //false
System.out.println(atomicStringReference.get()); //new value referenced