Collections.synchronizedList()方法的用途是什么?它似乎并未同步列表。

12 浏览
0 Comments

Collections.synchronizedList()方法的用途是什么?它似乎并未同步列表。

我正在尝试使用两个线程将String值添加到一个ArrayList中。我希望当一个线程正在添加值时,另一个线程不会干扰,所以我使用了Collections.synchronizedList方法。但是,如果我不明确在一个对象上同步,添加操作会以非同步的方式进行。

没有明确的同步块:

public class SynTest {
    public static void main(String []args){
        final List list=new ArrayList();
        final List 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()没有进行同步呢?

0