Collections.synchronizedList和synchronized [英] Collections.synchronizedList and synchronized
本文介绍了Collections.synchronizedList和synchronized的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
List<String> list = Collections.synchronizedList(new ArrayList<String>());
synchronized (list) {
list.add("message");
}
/ p>
Is the block "synchronized (list){} " really need here ?
推荐答案
您不需要像在示例中那样进行同步。但是,非常重要的是,当你迭代它时,你需要在列表之间同步(如Javadoc中所述):
You don't need to synchronize as you put in your example. HOWEVER, very important, you need to synchronize around the list when you iterate it (as noted in 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());
}
这篇关于Collections.synchronizedList和synchronized的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文