解决Concurrent Modification Exception

本文介绍了一种在线程并发环境下确保迭代器安全使用的方案。通过将List作为监视器进行同步,可以避免在迭代过程中其他线程对List进行修改而导致的异常情况。文章提供了具体的代码示例来说明如何实现这一机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原因:一个线程在用迭代器iterator的同时,另一个线程又在修改list数据

一种解决办法是

synchronize all access to the List, using the list itself as the monitor

code:
synchronized (list) {
for (Iterator it = list.iterator(); it.hashNext(); ) {
Foo f = (Foo) it.next();
// do what you need with f
}
}


Whatever other threads are modifying the list, they need to be synchronized too, also on the list. E.g.:

code:
syncronized (list) {
list.add(new Foo());
}


or

code:
syncronized (list) {
list.remove(oldFoo);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值