在同步列表的这两个用法之间的行为有什么区别 [英] What is the difference in behavior between these two usages of synchronized on a list

查看:126
本文介绍了在同步列表的这两个用法之间的行为有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

List<String> list = new ArrayList<String>();
list.add("a");
...
list.add("z");

synchronized(list) {
    Iterator<String> i = list.iterator();
    while(i.hasNext()) {
        ...
    }
}

List<String> list = new ArrayList<String>();
list.add("a");
...
list.add("z");

List<String> synchronizedList = Collections.synchronizedList(list);

synchronized(synchronizedList) {
    Iterator<String> i = synchronizedList.iterator();
    while(i.hasNext()) {
        ...
    }
}

$ b具体来说,我不清楚为什么 synchronized 在第二个实例中是必需的,当同步列表提供线程安全访问列表。

Specifically, I'm not clear as to why synchronized is required in the second instance when a synchronized list provides thread-safe access to the list.

推荐答案

如果你不锁定迭代,你会得到一个ConcurrentModificationException如果另一个线程修改它在循环。

If you don't lock around the iteration, you will get a ConcurrentModificationException if another thread modifies it during the loop.

同步所有方法并不能防止这种情况。

Synchronizing all of the methods doesn't prevent that in the slightest.

事情)是为什么 Collections.synchronized * 是完全无用的。

您应该使用 java.util.concurrent 。 (

This (and many other things) is why Collections.synchronized* is completely useless.
You should use the classes in java.util.concurrent. (and you should think carefully about how you will guarantee you will be safe)

作为一般的经验法则:


每个方法的锁定都不足以使线程安全。

Slapping locks around every method is not enough to make something thread-safe.

有关详细信息,请参见我的博客

For much more information, see my blog

这篇关于在同步列表的这两个用法之间的行为有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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