java – ArrayList在每个索引处返回0
发布时间:2020-12-15 04:31:40 所属栏目:Java 来源:网络整理
导读:所以我在这个练习中遇到了一些麻烦.我通过在每个线程中同步arraylist来解决其中一个问题,但仍然有问题. arraylist“data”用0到9999之间的数字填充.但是,data.get(i);似乎每个指数都会返回0,我不能为我的生活找出原因.这是代码: private static int LIST_TR
所以我在这个练习中遇到了一些麻烦.我通过在每个线程中同步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到10000之间的数字,其中i是当前元素的列表索引: 0 1 2 3 4 5 ... ^ i 当条件data.get(i)%(LIST_TRAVERSE_LIMIT / 3)== 0对列表的第一个元素(零)执行时,检查成功.然后,在列表的开头添加一个元素,该元素为负零(仍然为零),并继续下一个元素. 现在您的列表看起来像这样,但请注意我的内容: 0 0 1 2 3 4 .... ^ i 所以,看起来每个元素都是零,因为它是! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |