且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ArrayList 处理中的 java.util.ConcurrentModificationException

更新时间:2021-07-09 22:10:28

ArrayList 未同步.这意味着在您的 TimerThread 中,其他东西正在修改 ArrayList.

ArrayList is not synchronized. This means that in your TimerThread something else is modifying the ArrayList.

以下是文档的说明:

请注意,此实现不是同步的.如果多个线程同时访问一个 ArrayList 实例,并且至少有一个线程在结构上修改列表,它必须是同步的外部.(结构修改是任何增加或删除一个或多个元素,或显式调整后备数组的大小;仅仅设置元素的值不是结构性的修改.)这通常是通过同步一些自然封装列表的对象.如果不存在这样的对象,该列表应该使用 Collections.synchronizedList 进行包装"方法.这***在创建时完成,以防止意外对列表的非同步访问:

Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be "wrapped" using the Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list:

   List list = Collections.synchronizedList(new ArrayList(...));

使用 Collections.synchronizedList() 包装这个列表应该可以解决这个问题.

Wrapping this list using Collections.synchronizedList() should fix the problem.