在同步列表的这两个用法之间的行为有什么区别 [英] What is the difference in behavior between these two usages of synchronized on a list
问题描述
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屋!