如何在 Java 中声明数组元素 volatile? [英] How to declare array elements volatile in Java?

查看:58
本文介绍了如何在 Java 中声明数组元素 volatile?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 Java 中声明数组元素 volatile?即

Is there a way to declare array elements volatile in Java? I.e.

volatile int[] a = new int[10];

声明了数组引用 volatile,但是数组元素(例如a[1])仍然是不挥发.所以我正在寻找类似的东西

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 or AtomicReferenceArray

Use AtomicIntegerArray or AtomicLongArray or AtomicReferenceArray

AtomicIntegerArray 类实现了一个 int 数组,它的各个字段可以通过类的 get()set() 方法.从一个线程调用 arr.set(x, y) 将保证另一个调用 arr.get(x) 的线程将读取值 y(直到读取另一个值到位置 x).

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).

见:

这篇关于如何在 Java 中声明数组元素 volatile?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆