问题描述
有没有办法在Java中声明数组元素 volatile
?也就是说,它是一个非常简单的例子。
声明数组引用 volatile
,但是数组元素(例如 a [1]
)仍然不易变。所以我在寻找像
volatile int [] a = new volatile int [10]
但它不工作。
使用AtomicIntegerArray或AtomicLongArray
AtomicIntegerArray类实现了一个int数组,其各个字段可以通过类的get()和set()方法通过volatile语义访问。从一个线程调用arr.set(x,y)将保证另一个线程调用arr.get(x)将读取值y(直到另一个值被读取到位置x)。请参阅:
- 软件包摘要
Is there a way to declare array elements volatile
in Java? I.e.
volatile int[] a = new int[10];
declares the array reference volatile
, but the array elements (e.g. a[1]
) are still not volatile. So I'm looking for something like
volatile int[] a = new volatile int[10];
but it doesn't work that way. Is it possible at all?
use AtomicIntegerArray or AtomicLongArray
The AtomicIntegerArray class implements an int array whose individual fields can be accessed with volatile semantics, via the class's get() and set() methods. Calling arr.set(x, y) from one thread will then guarantee that another thread calling arr.get(x) will read the value y (until another value is read to position x).
See:
- AtomicIntegerArray
- AtomicLongArray
- java.util.concurrent.atomic Package Summary
这篇关于如何在Java中声明数组元素volatile?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!