Java 之 AtomicReference

java 之 AtomicReference

AtomicReference类提供了一个可以原子读写的对象引用变量。 原子意味着尝试更改相同AtomicReference的多个线程(例如,使用比较和交换操作)不会使AtomicReference最终达到不一致的状态。 AtomicReference甚至有一个先进的compareAndSet()方法,它可以将引用与预期值(引用)进行比较,如果它们相等,则在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);

String newReference = "new value referenced";
boolean exchanged = atomicStringReference.compareAndSet(initialReference, newReference);
System.out.println("exchanged: " + exchanged);

exchanged = atomicStringReference.compareAndSet(initialReference, newReference);
System.out.println("exchanged: " + exchanged);

推荐阅读更多精彩内容