Collections.synchronizedList 和同步 [英] Collections.synchronizedList and synchronized

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

问题描述

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

这里真的需要同步(列表){}"块吗?

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 和同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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