gpt4 book ai didi

java - Collections.synchronizedList 和同步

转载 作者:IT老高 更新时间:2023-10-28 13:52:24 30 4
gpt4 key购买 nike

List<String> list = Collections.synchronizedList(new ArrayList<String>());
synchronized (list) {
list.add("message");
}

这里真的需要 block “同步(列表){}”吗?

最佳答案

您不需要像您在示例中那样进行同步。但是,非常重要的是,您需要在迭代时围绕列表进行同步(如 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());
}

关于java - Collections.synchronizedList 和同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9468187/

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