Iterator.next()上的ConcurrentModificationException [英] ConcurrentModificationException on Iterator.next()

查看:352
本文介绍了Iterator.next()上的ConcurrentModificationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在以下代码上收到ConcurrentModificationException:

I am getting a ConcurrentModificationException on the following code:

private static List<Task> tasks = new LinkedList<Task>();
...
public void doTasks(){
    synchronized(tasks){
        Iterator<Task> it = tasks.iterator();

        while(it.hasNext()){
            Task t = it.next(); < Exception is always thrown on this line.

            if(t.isDone()){
                it.remove();
            } else {
                t.run();
            }
        }
    }
}
...
public void addTask(Task t){
    synchronized(tasks){
        tasks.add(t);
    }
}
...
public void clearTasks(){
    synchronized(tasks){
        tasks.clear();
    }
}

在类中的其他任何地方都没有使用对象任务".我不确定为什么会收到例外.任何帮助将不胜感激.

The Object "tasks" is not used anywhere else in the class. I'm not sure why I'm getting the exception. Any help would be greatly appreciated.

推荐答案

这是您的问题:

if(t.isDone()){
    ...
} else {
    t.run(); // probably changing the task, so consequently the list tasks
}

您无法在循环中更改tasks列表.查看 ConcurrentModificationException文档以获取更多信息详细信息.

you can't change the tasks list in the loop. Check out the ConcurrentModificationException documentation for more details.

干杯!

这篇关于Iterator.next()上的ConcurrentModificationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆