【发布时间】:2016-12-02 11:10:40
【问题描述】:
我正在尝试使用两个线程将 String 值添加到 ArrayList。我想要的是,当一个线程添加值时,另一个线程不应该干扰,所以我使用了Collections.synchronizedList 方法。但似乎如果我没有在对象上显式同步,则添加是以非同步方式完成的。
没有显式同步块:
public class SynTest {
public static void main(String []args){
final List<String> list=new ArrayList<String>();
final List<String> synList=Collections.synchronizedList(list);
final Object o=new Object();
Thread tOne=new Thread(new Runnable(){
@Override
public void run() {
//synchronized(o){
for(int i=0;i<100;i++){
System.out.println(synList.add("add one"+i)+ " one");
}
//}
}
});
Thread tTwo=new Thread(new Runnable(){
@Override
public void run() {
//synchronized(o){
for(int i=0;i<100;i++){
System.out.println(synList.add("add two"+i)+" two");
}
//}
}
});
tOne.start();
tTwo.start();
}
}
我得到的输出是:
true one
true two
true one
true two
true one
true two
true two
true one
true one
true one...
在未注释显式同步块的情况下,我将在添加时停止来自其他线程的干扰。一旦线程获得了锁,它就会一直执行直到完成。
取消注释同步块后的示例输出:
true one
true one
true one
true one
true one
true one
true one
true one...
那么为什么Collections.synchronizedList() 不进行同步呢?
【问题讨论】:
-
你期待什么?重复
one two one two one two...?同步是在列表操作上,而不是在线程上 -
看一下 SynchronizedList 的代码,了解同步是如何实现的:grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/…
标签: java multithreading collections synchronization