【发布时间】:2019-04-23 07:16:15
【问题描述】:
一个线程从数组的一个索引读取,而另一个线程写入数组的另一个索引,是否存在任何并发问题,只要索引不同?
例如(这个例子不一定推荐实际使用,只是为了说明我的观点)
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);
}
}
编辑: 批评这个例子不是我的问题,我实际上只是想知道数组访问一个索引,同时访问另一个索引,是否会造成并发问题,想不出简单的例子。
【问题讨论】:
标签: java arrays concurrency thread-safety