在我想要运行的每个线程中,这类代码初始化列表
final int initialSize = 2000;
final Random rand = new Random(System.currentTimeMillis());
Thread creationThread = new Thread(new Runnable() {
@Override
public void run() {
for (int j = 0; j < initialSize; j++) {
list.add(rand.nextInt(10000));
}
}
});
creationThread.start();
creationThread.join();
List<Thread> threads = new ArrayList<Thread>();
final int threadElemAmount = initialSize / numberOfThreads;创建用于删除的线程
for (int i = 0; i < numberOfThreads; i++) {
threads.add(new Thread(new Runnable() {
@Override
public void run() {
for (int j = 0; j < threadElemAmount; j++) {
list.remove((int) (list.size() - 1));
}
}
}));
}但是我遇到了ArrayIndexOutOfBoundsException的读写问题。如何避免这种情况?
发布于 2015-11-22 21:29:43
如果您只想确保删除操作成功,那么请按列表同步代码,如下所示:
public void run() {
for (int j = 0; j < threadElemAmount; j++) {
synchronized (list) {
list.remove((int) (list.size() - 1));
}
}
}同时,您也可以放心地使用相同的列表实例进行同步。
这个问题是由下面这行代码引起的:
list.remove((int) (list.size() - 1));是这样处理的:
1: int tempVal = list.size() - 1;
2: list.remove(tempVal);在您的示例中,线程A正在执行第1行,将执行上下文传递给线程B,线程B执行1和2,然后线程A抛出异常。
https://stackoverflow.com/questions/33855156
复制相似问题