所以我在练习时遇到了一些麻烦。我通过在每个线程中同步arraylist来解决其中一个问题,但仍然有问题。 arraylist“data”用0到9999之间的数字填充。但是,data.get(i);似乎每个指数都会返回0,我不能为我的生活找出原因。这是代码:
private static int LIST_TRAVERSE_LIMIT = 10000; // size of problem
private boolean problem_3_failed = false; // set to true if failed
private List<Integer> data = new ArrayList<Integer>(); // data shared between threads, traversed and modified
private int negative_hits = 0; // counter for how many modifications are found during traversal
private void test_parallel_iteration() {
for(int i=0; i<LIST_TRAVERSE_LIMIT; i++) data.add(i);
// Define threads and run them
Thread t1 = new Thread(() -> { // modify the list in just a few places
synchronized(data){
for(int i=0; i<LIST_TRAVERSE_LIMIT; i++)
if(data.get(i)%(LIST_TRAVERSE_LIMIT/3)==0) data.add(0, -data.get(i));
}
});
Thread t2 = new Thread(() -> { // iterate the list
try {
synchronized(data){
for(int i: data)
if(i<0) {
System.out.println("Found negative number: "+i);
negative_hits++;
}
}
} catch(ConcurrentModificationException exn) {
System.out.println("Problem 3, thread 2 failed: concurrent modification");
problem_3_failed = true;
}
});
finish(t1,t2);
// What happened?
System.out.println("#Negative hits: "+negative_hits);
if(problem_3_failed) System.out.println("Problem 3 failed");
else System.out.println("Problem 3 succeeded");
}
private void finish(Thread t1, Thread t2) {
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
throw new Error("Internal error: interrupted!");
}
}
输出:
#Negative hits: 0
Problem 3 succeeded
答案 0 :(得分:7)
你正在把自己编程成一个无限循环。方法如下:
您的列表是一系列0到10000之间的数字,其中i
是当前元素的列表索引:
0 1 2 3 4 5 ...
^
i
当条件data.get(i)%(LIST_TRAVERSE_LIMIT/3)==0
对列表的第一个元素(零)执行时,检查成功。然后,在列表的开头添加一个元素,该元素为负零(仍然为零),并继续下一个元素。
现在您的列表看起来像这样,但请注意i
的内容:
0 0 1 2 3 4 ....
^
i
所以,看起来每个元素都是零,因为它是!