问题描述
一个线程从数组的一个索引读取,而另一个线程写入数组的另一个索引,只要索引不同,是否存在并发问题?
Are there any concurrency problems with one thread reading from one index of an array, while another thread writes to another index of the array, as long as the indices are different?
例如(这个例子不一定推荐实际使用,只是为了说明我的观点)
e.g. (this example not necessarily recommended for real use, only to illustrate my point)
class Test1
{
static final private int N = 4096;
final private int[] x = new int[N];
final private AtomicInteger nwritten = new AtomicInteger(0);
// invariant:
// all values x[i] where 0 <= i < nwritten.get() are immutable
// read() is not synchronized since we want it to be fast
int read(int index) {
if (index >= nwritten.get())
throw new IllegalArgumentException();
return x[index];
}
// write() is synchronized to handle multiple writers
// (using compare-and-set techniques to avoid blocking algorithms
// is nontrivial)
synchronized void write(int x_i) {
int index = nwriting.get();
if (index >= N)
throw SomeExceptionThatIndicatesArrayIsFull();
x[index] = x_i;
// from this point forward, x[index] is fixed in stone
nwriting.set(index+1);
}
}
批评这个例子不是我的问题,我真的只是想知道数组访问一个索引,同时访问另一个索引,是否会带来并发问题,想不出一个简单的例子.
edit: critiquing this example is not my question, I literally just want to know if array access to one index, concurrently to access of another index, poses concurrency problems, couldn't think of a simple example.
推荐答案
虽然您不会通过更改数组获得无效状态,但是当两个线程正在查看非易失性整数时,您将遇到同样的问题同步(请参阅 Java 教程中关于内存一致性错误).基本上,问题在于线程 1 可能会在空间 i 中写入一个值,但无法保证线程 2 何时(或是否)会看到更改.
类 java.util.concurrent.atomic.AtomicIntegerArray
做你想做的事.
The class java.util.concurrent.atomic.AtomicIntegerArray
does what you want to do.
这篇关于Java 中的数组是线程安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!