有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (5) 个答案

  1. # 1 楼答案

    看起来它在功能上相当于AtomicReference[],但占用的内存少了一点

    因此,当你需要超过一百万个原子引用时,它是有用的——你想不出任何用例

  2. # 2 楼答案

    如果你有大量同时更新的对象,比如在大型多人游戏中,它可能会很有用

    参考i的更新将遵循以下模式

    boolean success = false;
    while (!success)
    {
        E previous = atomicReferenceArray.get(i);
        E next = ... // compute updated object
        success = atomicReferenceArray.compareAndSet(i, previous, next);
    }
    

    根据具体情况,这可能比锁定更快和/或更容易使用(synchronized

  3. # 3 楼答案

    import java.util.concurrent.atomic.AtomicReferenceArray;
    
    public class AtomicReferenceArrayExample {
        AtomicReferenceArray<String> arr = new AtomicReferenceArray<String>(10);
    
        public static void main(String... args) {
            new Thread(new AtomicReferenceArrayExample().new AddThread()).start();
            new Thread(new AtomicReferenceArrayExample().new AddThread()).start();
        }
    
        class AddThread implements Runnable {
            @Override
            public void run() {
                // Sets value at the index 1
                arr.set(0, "A");
                // At index 0, if current reference is "A" then it changes as "B".
                arr.compareAndSet(0, "A", "B");
                // At index 0, if current value is "B", then it is sets as "C".
                arr.weakCompareAndSet(0, "B", "C");
                System.out.println(arr.get(0));
            }
        }
    
    }
    
    //    Result:
    //        C
    //        C
    
  4. # 4 楼答案

    一个可能的用例是ConcurrentHashMap,它在内部广泛使用数组。数组可以是易变的,但在每元素级别的语义不能是易变的。这也是automic阵列诞生的原因之一

  5. # 5 楼答案

    如果有对象引用的共享数组,那么可以使用AtomicReferenceArray来确保数组不能由不同的线程同时更新,即一次只能更新一个元素

    然而,在AtomicReference[](数组AtomicReference)中,多个线程仍然可以模拟地更新不同的元素,因为原子性在元素上,而不是整个数组上

    更多信息here