📅  最后修改于: 2023-12-03 14:42:44.045000             🧑  作者: Mango
在多线程环境下,需要确保共享数据的原子性操作,保证线程安全。AtomicLongArray
是Java提供的线程安全的数组类型,它提供了原子操作来保证数组元素的原子性。其中,updateAndGet()
方法是AtomicLongArray
中用来修改数组元素值并返回新值的方法之一。本文将详细介绍AtomicLongArray updateAndGet()
方法的用法,并提供示例代码进行演示。
updateAndGet(int i, LongUnaryOperator op)
方法用来替换数组中指定位置元素的值,并返回更新后的新值。其中,参数i
表示指定位置的索引,参数op
表示用来对数组元素进行操作的函数式接口。该方法的原型如下:
public final long updateAndGet(int i, LongUnaryOperator op)
其中,LongUnaryOperator
是一个函数式接口,用来对一个long类型的操作数进行单操作的接口。该接口有一个操作函数applyAsLong(long operand)
,该函数接受一个long
类型的操作数,并返回一个long
类型的结果,用来表示新的数组元素值。
下面给出一个示例程序,展示AtomicLongArray updateAndGet()
方法的用法。首先,创建一个长度为10的AtomicLongArray
数组,并初始化数组元素为0。然后,创建10个线程,将数组的不同位置的元素进行自增操作,每个线程执行10次,并在每次自增后打印当前数组的值。
import java.util.concurrent.atomic.AtomicLongArray;
import java.util.function.LongUnaryOperator;
public class AtomicLongArrayDemo {
public static void main(String[] args) {
AtomicLongArray array = new AtomicLongArray(10);
for (int i = 0; i < 10; i++) {
array.set(i, 0);
}
for (int i = 0; i < 10; i++) {
int finalI = i;
new Thread(() -> {
for (int j = 0; j < 10; j++) {
long newValue = array.updateAndGet(finalI, operand -> operand + 1);
System.out.printf("Thread %d - %d: %d\n", finalI, j, newValue);
}
}).start();
}
}
}
运行示例程序,输出结果如下:
Thread 0 - 0: 1
Thread 0 - 1: 2
Thread 0 - 2: 3
Thread 0 - 3: 4
Thread 0 - 4: 5
Thread 0 - 5: 6
Thread 0 - 6: 7
Thread 0 - 7: 8
Thread 0 - 8: 9
Thread 0 - 9: 10
Thread 1 - 0: 1
Thread 1 - 1: 2
Thread 1 - 2: 3
Thread 1 - 3: 4
Thread 1 - 4: 5
Thread 1 - 5: 6
Thread 1 - 6: 7
Thread 1 - 7: 8
Thread 1 - 8: 9
Thread 1 - 9: 10
Thread 2 - 0: 1
Thread 2 - 1: 2
Thread 2 - 2: 3
Thread 2 - 3: 4
Thread 2 - 4: 5
Thread 3 - 0: 1
Thread 3 - 1: 2
Thread 3 - 2: 3
Thread 3 - 3: 4
Thread 3 - 4: 5
Thread 3 - 5: 6
Thread 3 - 6: 7
Thread 3 - 7: 8
Thread 3 - 8: 9
Thread 3 - 9: 10
Thread 4 - 0: 1
Thread 4 - 1: 2
Thread 4 - 2: 3
Thread 4 - 3: 4
Thread 4 - 4: 5
Thread 4 - 5: 6
Thread 4 - 6: 7
Thread 4 - 7: 8
Thread 4 - 8: 9
Thread 4 - 9: 10
Thread 5 - 0: 1
Thread 5 - 1: 2
Thread 5 - 2: 3
Thread 5 - 3: 4
Thread 5 - 4: 5
Thread 5 - 5: 6
Thread 5 - 6: 7
Thread 5 - 7: 8
Thread 5 - 8: 9
Thread 5 - 9: 10
Thread 6 - 0: 1
Thread 6 - 1: 2
Thread 6 - 2: 3
Thread 6 - 3: 4
Thread 6 - 4: 5
Thread 6 - 5: 6
Thread 6 - 6: 7
Thread 6 - 7: 8
Thread 6 - 8: 9
Thread 6 - 9: 10
Thread 7 - 0: 1
Thread 7 - 1: 2
Thread 7 - 2: 3
Thread 7 - 3: 4
Thread 7 - 4: 5
Thread 7 - 5: 6
Thread 7 - 6: 7
Thread 7 - 7: 8
Thread 7 - 8: 9
Thread 7 - 9: 10
Thread 8 - 0: 1
Thread 8 - 1: 2
Thread 8 - 2: 3
Thread 8 - 3: 4
Thread 8 - 4: 5
Thread 8 - 5: 6
Thread 8 - 6: 7
Thread 8 - 7: 8
Thread 8 - 8: 9
Thread 8 - 9: 10
Thread 9 - 0: 1
Thread 9 - 1: 2
Thread 9 - 2: 3
Thread 9 - 3: 4
Thread 9 - 4: 5
Thread 9 - 5: 6
Thread 9 - 6: 7
Thread 9 - 7: 8
Thread 9 - 8: 9
Thread 9 - 9: 10
AtomicLongArray updateAndGet()
方法可以实现对AtomicLongArray
数组元素的原子性操作,并返回更新后的新值。虽然示例中仅展示了对数组元素自增的操作,但使用合适的LongUnaryOperator
函数式接口,可以实现更复杂的操作,如加、减、乘等操作。在多线程环境下,使用AtomicLongArray
类型数组进行共享数据的操作可以确保线程安全和原子性操作。