所以我在这个练习中遇到了一些麻烦.我通过在每个线程中同步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 Listdata = new ArrayList (); // 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 { // modify the list in just a few places synchronized(data){ for(int i=0; i { // 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
nickb.. 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
所以,看起来每个元素都是零,因为它是!
你正在编程自己进入无限循环.这是如何做:
您的列表是一系列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
所以,看起来每个元素都是零,因为它是!