📌  相关文章
📜  AtomicReferenceArray类

📅  最后修改于: 2020-11-15 03:55:59             🧑  作者: Mango


java.util.concurrent.atomic.AtomicReferenceArray类提供了对基础引用数组的操作,这些操作可以原子方式读写,并且还包含高级原子操作。 AtomicReferenceArray支持对基础引用数组变量的原子操作。它具有get和set方法,它们的工作方式类似于对易失性变量的读写。也就是说,一个集合与该变量的任何后续get都具有事前发生的关系。原子compareAndSet方法还具有这些内存一致性功能。

AtomicReferenceArray方法

以下是AtomicReferenceArray类中可用的重要方法的列表。

Sr.No. Method & Description
1

public boolean compareAndSet(int i, E expect, E update)

Atomically sets the element at position i to the given updated value if the current value == the expected value.

2

public E get(int i)

Gets the current value at position i.

3

public E getAndSet(int i, E newValue)

Atomically sets the element at position i to the given value and returns the old value.

4

public void lazySet(int i, E newValue)

Eventually sets the element at position i to the given value.

5

public int length()

Returns the length of the array.

6

public void set(int i, E newValue)

Sets the element at position i to the given value.

7

public String toString()

Returns the String representation of the current values of array.

8

public boolean weakCompareAndSet(int i, E expect, E update)

Atomically sets the element at position i to the given updated value if the current value == the expected value.

以下TestThread程序显示了在基于线程的环境中AtomicReferenceArray变量的用法。

import java.util.concurrent.atomic.AtomicReferenceArray;

public class TestThread {
   private static String[] source = new String[10];
   private static AtomicReferenceArray atomicReferenceArray 
      = new AtomicReferenceArray(source);

   public static void main(final String[] arguments) throws InterruptedException {

      for (int i = 0; i

这将产生以下结果。

输出

Thread 9, index 0, value: item-2
Thread 10, index 0, value: item-1
Item swapped: false
Thread 10, index 1, value: item-2
Item swapped: true
Thread 9, index 1, value: updated-item-2
Thread 10, index 1, updated-item-2
Thread 10, index 2, value: item-3
Item swapped: false
Thread 10, index 3, value: item-2
Item swapped: true
Thread 10, index 3, updated-item-2
Thread 10, index 4, value: item-2
Item swapped: true
Thread 10, index 4, updated-item-2
Thread 10, index 5, value: item-2
Item swapped: true
Thread 10, index 5, updated-item-2
Thread 10, index 6, value: item-2
Thread 9, index 2, value: item-2
Item swapped: true
Thread 9, index 3, value: updated-item-2
Thread 10, index 6, updated-item-2
Thread 10, index 7, value: item-2
Thread 9, index 4, value: updated-item-2
Item swapped: true
Thread 9, index 5, value: updated-item-2
Thread 10, index 7, updated-item-2
Thread 9, index 6, value: updated-item-2
Thread 10, index 8, value: item-2
Thread 9, index 7, value: updated-item-2
Item swapped: true
Thread 9, index 8, value: updated-item-2
Thread 10, index 8, updated-item-2
Thread 9, index 9, value: item-2
Thread 10, index 9, value: item-10
Item swapped: false