Java 之 AtomicReference

作者: 熬夜的猫头鹰 | 来源:发表于2018-06-16 23:29 被阅读8次

    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);
    
    

    相关文章

      网友评论

        本文标题:Java 之 AtomicReference

        本文链接:https://www.haomeiwen.com/subject/mqrieftx.html