嘿 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)
仔细研究了一下,这似乎是线程通常会发生的错误,为什么它们会尝试并发访问相同的资源,但这就是让我在这个系统中根本不是多线程的原因。
谁能解释为什么会这样,或者想出一个 hack 来绕过它
非常感谢^_^
最佳答案
您可以修改Iterator
的底层Collection
(隐藏在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();
}
}
关于非多线程程序中的java.util.ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1816196/