[英]Code produces Concurrent Modification Exception
I've got the following code: 我有以下代码:
public static void pauseAllTimers() {
for(Timer timer : Timer.allTimers) {
timer.pause();
}
}
Where Timer
instances are being added and removed to allTimers
within one thread (as far as I can tell, unless I'm overseeing something in my code). 在一个线程内将
Timer
实例添加到allTimers
或从中删除的情况(据我所知,除非我监督代码中的内容)。
Why is my code yielding a Concurrent Modification Exception? 为什么我的代码会产生并发修改异常?
You're iterating over the collection while you're removing from it - assuming that pause()
removes the timer. 从集合中删除时,您正在遍历整个集合-假设
pause()
会删除计时器。 Don't do that - you're modifying a collection while you're still iterating over it, which is a concurrent modification even though there's only one thread. 不要这样做-在修改集合的同时仍要对其进行迭代,即使只有一个线程,这也是并发修改。
Copy the set of timers to a list, and then iterate over that : 设定定时器复制到一个列表,然后遍历是 :
List<Timer> timers = new ArrayList<Timer>(Timer.allTimers);
for (Timer timer : timers) {
timer.pause();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.