小编典典

非多线程程序中的java.util.ConcurrentModificationException

java

嘿,SO Guru的即时通讯工作非常顺利,

public void kill(double GrowthRate, int Death)
{
    int before = population.size();
    for (PopulationMember p : population)
    {
        int[] probs = ProbablityArrayDeath(GrowthRate,Death,(int)p.fitness());
        if (probs[RandomNumberGen.nextRandomInt(0, 99)]==0)
        {
            population.remove(p);
        }
    }
    System.out.println("Intial Population: "+before+", Deaths:"+(before-          population.size())+", New Population: "+population.size());
}

当我第一次运行程序时,它尝试运行代码时遇到此错误

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)
    at java.util.HashMap$KeyIterator.next(HashMap.java:828)
    at Genetics.Population.kill(Population.java:181)
    at Genetics.Population.run(Population.java:47)
    at Control.Main.main(Main.java:35)

经过一番摸索,这似乎是线程通常会发生的错误,为什么它们尝试同时访问同一资源,但这就是让我在该系统中根本不使用多线程的原因。

有人可以解释为什么会这样,还是想办法解决它

非常感谢^ _ ^


阅读 210

收藏
2020-10-20

共1个答案

小编典典

您可以修改底层CollectionIterator(这是隐藏在for-each环)。正确的方法是:

for (Iterator<PopulationMember> it = population.iterator(); it.hasNext();) {
    PopulationMemeber p = it.next();
    int[] probs = ProbablityArrayDeath(GrowthRate,Death,(int)p.fitness());
    if (probs[RandomNumberGen.nextRandomInt(0, 99)] == 0) {
        it.remove();
    }
}
2020-10-20