有两个线程访问一个经常更新的ArrayList问题 [英] Problems with two threads accessing a frequently updated Arraylist

查看:208
本文介绍了有两个线程访问一个经常更新的ArrayList问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有许多存储对象的ArrayList和对象经常添加,并从的ArrayList中删除。一个线程上操作的数据结构,并且更新每20ms左右ArrayList的对象。另一个线程遍历的ArrayList和使用它们的元素来绘制对象(也每20-30ms)。

I have ArrayLists that store many objects, and objects are frequently added and removed from the ArrayLists. One thread operates on the data structures and updates the ArrayList's objects every 20ms or so. Another thread traverses the ArrayLists and uses their elements to paint the objects (also every 20-30ms).

如果在的ArrayList使用一个for循环遍历,IndexOutOfBoundsExceptions比比皆是。如果的ArrayList使用迭代器遍历,ConcurrentModificationExceptions比比皆是。同步像这样的ArrayList

If the ArrayLists are traversed using a for loop, IndexOutOfBoundsExceptions abound. If the ArrayLists are traversed using iterators, ConcurrentModificationExceptions abound. Synchronizing the ArrayLists like so:


List list = Collections.synchronizedList(new ArrayList());
synchronized(list) {
//use iterator for traversals
}

没有抛出异常,但有一个显着的性能消耗。有没有一种方法来遍历这些不用的ArrayList例外是罚球,并且没有表现流失?

Throws no exceptions but has a substantial performance drain. Is there a way to traverse these ArrayLists without exceptions being throw, and without a performance drain?

谢谢!

推荐答案

一个好办法解决这个问题是使线程上的列表中的不同拷贝工作。然而,的CopyOnWriteArrayList 不适合在这里很好,因为它是在每次修改创建一个副本,但在你的情况下,它会更好地创建副本那么频繁。

A good approach to this problem is to make threads work on different copies of the list. However, CopyOnWriteArrayList doesn't fit here well, since it creates a copy at every modification, but in your case it would be better to create copies less frequent.

所以,你可以手动实现:第一个线程创建的更新列表的副本,并通过挥发性变量将其出版,第二个线程在该副本中工作(我认为第一个线程仅修改列表,而不是在它的对象):

So, you can implement it manually: the first thread creates a copy of the updated list and publishes it via the volatile variable, the second thread works with this copy (I assume that the first thread modifies only list, not objects in it):

private volatile List publicList;

// Thread A
List originalList = ...;
while (true) {
    modifyList(originalList); // Modify list
    publicList = new ArrayList(originalList); // Pusblish a copy
}

// Thread B
while (true) {
    for (Object o: publicList) { // Iterate over a published copy
        ...
    }
}

这篇关于有两个线程访问一个经常更新的ArrayList问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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