【问题标题】:ConcurrentModificationException in iterator.next() Multithreaded [duplicate]iterator.next() 中的 ConcurrentModificationException 多线程 [重复]
【发布时间】:2017-02-10 04:30:48
【问题描述】:

我创建了这个简单的工作线程,通过遍历 ArrayList 来计算回文。 当我执行 line temp_str1 = it.next(); 时出现错误。 ArrayList buffer_List 不被任何其他线程使用,因此使用同步块没有帮助。我已经查看了以前的问题,但它们并没有太大帮助。我渴望找到解决这个问题的方法。

这是我的代码:

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++;
        }
    }
}

编辑代码:添加到_Shared_Queue

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

【问题讨论】:

  • 看看这个人的回答,或许能帮到你。这是您用来从 ArrayList 中删除项目的 remove 方法。 stackoverflow.com/questions/15993356/…
  • 我打赌你正在修改 to_Shared_Queue 方法中的 buffer_List。
  • @MGorgon:这也是我的赌注,但到底谁知道呢。
  • @MGorgon 我只在 to_Shared_Queue 的参数中发送字符串 temp_str1,因此不会修改列表。

标签: java multithreading arraylist iterator concurrentmodification


【解决方案1】:

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

【讨论】:

  • 这看起来与我们的建议完全相反。
猜你喜欢
  • 1970-01-01
  • 2011-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
  • 2019-03-12
  • 2021-03-02
  • 1970-01-01
相关资源
最近更新 更多