我使用了同步列表,我仍然得到ConcurrentModificationException [英] I used synchronized list, and i still get ConcurrentModificationException

查看:120
本文介绍了我使用了同步列表,我仍然得到ConcurrentModificationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Vector 而不是 ArrayList 来使列表在多线程环境中安全无虞。但是当我尝试在迭代它时将项目添加到 Vector 时,我一直得到 ConcurrentModificationException 。为什么会这样呢?如何防止它?

I'm using Vector instead of ArrayList to make a list safe in multi-threaded enviroment. But I keep getting ConcurrentModificationException when I trying to add items to the Vector while iterating it. Why is that and how can I prevent it?

推荐答案

迭代时不能修改Vector。将项目存储在一个单独的向量中,并在循环结束时将它们移动到Vector,或者循环遍历原始Vector的副本。

You cannot modify a Vector while iterating over it. Store the items to add in a separate vector, and move them to the Vector when the loop is finished or loop over a copy of the original Vector.

增加:
要在java中获取Vector周围的互斥锁,请在两个函数中执行此操作:

ADDED: To get a mutex around the Vector in java, do this in both functions:

synchronized (list) {
  // modifying list
}

和:

synchronized (list) {
  // iterating over list
}

当然我假设列表名为 list

这篇关于我使用了同步列表,我仍然得到ConcurrentModificationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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