iterator.next()中的ConcurrentModificationException多线程

时间:2016-10-01 20:22:32

标签: java multithreading arraylist iterator concurrentmodification

我创建了这个简单的工作线程,通过迭代ArrayList来计算回文。 当我执行temp_str1 = it.next();行时出错。 任何其他线程都不使用ArrayList buffer_List,因此使用synchronized块没有帮助。我查看过以前的问题并没有多大帮助。我渴望找到这个问题的解决方案。

这是我的代码:

private void find_Palindromes(ArrayList<String> buffer_List){
    Iterator<String> it = buffer_List.iterator();
    String temp_str1, temp_str2;
    while(it.hasNext()){
        temp_str1 = it.next();
        //System.out.println(temp_str1);
        it.remove();

        if(is_Palindrome(temp_str1)){
            to_Shared_Queue(temp_str1);
            palin_count++;
        }
    }
}
  

编辑代码:添加到_hared_Queue

  private void to_Shared_Queue(String str){           
        synchronized(shared_queue){
            Shared_queue.add(str);
        }
  }

1 个答案:

答案 0 :(得分:-2)

这是因为你在循环它时修改迭代器。你可以通过从数组buffer_List中删除它来做到这一点。 buffer_List.remove(temp_str1);

相关问题