📜  Java并发-AtomicLongArray类

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


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

AtomicLongArray方法

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

Sr.No. Method & Description
1

public long addAndGet(int i, long delta)

Atomically adds the given value to the element at index i.

2

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

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

3

public long decrementAndGet(int i)

Atomically decrements by one the element at index i.

4

public long get(int i)

Gets the current value at position i.

5

public long getAndAdd(int i, long delta)

Atomically adds the given value to the element at index i.

6

public long getAndDecrement(int i)

Atomically decrements by one the element at index i.

7

public long getAndIncrement(int i)

Atomically increments by one the element at index i.

8

public long getAndSet(int i, long newValue)

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

9

public long incrementAndGet(int i)

Atomically increments by one the element at index i.

10

public void lazySet(int i, long newValue)

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

11

public int length()

Returns the length of the array.

12

public void set(int i, long newValue)

Sets the element at position i to the given value.

13

public String toString()

Returns the String representation of the current values of array.

14

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

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

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

import java.util.concurrent.atomic.AtomicLongArray;

public class TestThread {
   private static AtomicLongArray atomicLongArray = new AtomicLongArray(10);

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

      for (int i = 0; i

这将产生以下结果。

输出

Thread 9, index 0, value: 2
Thread 10, index 0, value: 3
Thread 9, index 1, value: 2
Thread 9, index 2, value: 2
Thread 9, index 3, value: 2
Thread 9, index 4, value: 2
Thread 10, index 1, value: 3
Thread 9, index 5, value: 2
Thread 10, index 2, value: 3
Thread 9, index 6, value: 2
Thread 10, index 3, value: 3
Thread 9, index 7, value: 2
Thread 10, index 4, value: 3
Thread 9, index 8, value: 2
Thread 9, index 9, value: 2
Thread 10, index 5, value: 3
Thread 10, index 6, value: 3
Thread 10, index 7, value: 3
Thread 10, index 8, value: 3
Thread 10, index 9, value: 3
Values: 
3 3 3 3 3 3 3 3 3 3