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

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

问题描述

有没有办法在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:

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

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