数组在 Java 中是线程安全的吗?
2022-09-01 12:11:29
只要索引不同,一个线程从数组的一个索引读取,而另一个线程写入数组的另一个索引,是否存在任何并发问题?
例如(这个例子不一定推荐用于实际使用,只是为了说明我的观点)
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);
}
}
编辑:批评这个例子不是我的问题,我真的只是想知道数组访问一个索引,并发访问另一个索引,会带来并发问题,想不出一个简单的例子。