Java同步列表 [英] Java Synchronized list

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

问题描述

我有一个预先填充的数组列表。我有多个线程将从数组列表中删除元素。每个线程调用下面的remove方法,并从列表中删除一个项目。以下代码是否为我提供了一致的行为?

I have a pre-populated array list. And I have multiple threads which will remove elements from the array list. Each thread calls the remove method below and removes one item from the list. Does the following code give me consistent behavior ?

ArrayList<String> list = Collections.synchronizedList(new ArrayList<String>());

void remove(String item)
{
     do something; (doesn't work on the list)
     list.remove(item);
}

谢谢!

推荐答案

是的,如果您也在遍历列表,请小心,因为在这种情况下,您需要对其进行同步。来自 Javadoc

Yes, Just be careful if you are also iterating over the list, because in this case you will need to synchronize on it. From the Javadoc:


当迭代时,用户必须手动同步返回的列表:

It is imperative that the user manually synchronize on the returned list when iterating over it:



List list = Collections.synchronizedList(new ArrayList());
    ...
synchronized (list) {
    Iterator i = list.iterator(); // Must be in synchronized block
    while (i.hasNext())
        foo(i.next());
}

或者,您可以使用 CopyOnWriteArrayList 写入速度较慢但没有此问题。

Or, you can use CopyOnWriteArrayList which is slower for writes but doesn't have this issue.

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

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