gpt4 book ai didi

Java 同步列表

转载 作者:IT老高 更新时间:2023-10-28 13:53:12 26 4
gpt4 key购买 nike

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

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

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

谢谢!

最佳答案

是的,如果您还对列表进行迭代,请小心,因为在这种情况下,您需要对其进行同步。来自 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,它的写入速度较慢,但​​没有此问题。

关于Java 同步列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11360401/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com