问题描述
如何使数组变得易变?因为我已经理解,使数组变得不稳定是不安全的?
How do I make an array volatile? Because as I've come to understand, it's unsafe to make an array volatile?
推荐答案
声明一个数组volatile 不提供对其字段的易失性访问。你声明引用本身是易变的,而不是它的元素。
Declaring an array volatile does not give volatile access to it's fields. You're declaring the reference itself volatile, not its elements.
换句话说,你宣布一个易变的元素,而不是一组易变元素。
这里的解决方案是使用 AtomicIntegerArray
以防你想使用整数。
In other words you're declaring a volatile set of elements, not a set of volatile elements.The solution here is to use AtomicIntegerArray
in case you want to use integers.
另一种方式(但有点难看的是每次编辑字段时都要重写对数组的引用。
Another way (but kinda ugly) is to rewrite the reference to the array every time you edit a field.
你这样做:
arr = arr;
(正如我所说......丑陋)
(as I said... ugly)
这篇关于Java volatile数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!