下面这段代码是非线程安全的package org.luyang.thread;import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Vector;public class UnSafeThread extends Thread {
    UnSafeObject unSafe;    int dest;    int value;    String id;    public static void main(String[] args) {
        UnSafeObject unSafe = new UnSafeObject();
        Thread a = new UnSafeThread(unSafe, 0, 3, "TA");
        Thread b = new UnSafeThread(unSafe, 0, 33, "TB");
        a.start();
        b.start();
    }    public UnSafeThread() {
    }    public UnSafeThread(UnSafeObject o, int dest, int value, String id) {
        unSafe = o;
        this.dest = dest;
        this.value = value;
        this.id = id;
    }    public void run() {
     System.out.println(Thread.currentThread().getName());
        unSafe.l.add(dest, new Integer(value));
        System.out.println(id + "的位置" + dest + " is now " + value);
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // unSafe.l.get(dest);
        System.out.println(id + "的位置" + dest + " = " + unSafe.l.get(dest));
    }
}class UnSafeObject {
     List l = new ArrayList();    static UnSafeObject obj = new UnSafeObject();    public UnSafeObject() {
    }}运行结果:
Thread-0
TA的位置0 is now 3
Thread-1
TB的位置0 is now 33
TA的位置0 = 33
TB的位置0 = 33========================================但是: 把 上面的 class UnSafeObject 中的 
 List l = new ArrayList();
 改为:
 List l = Collections.synchronizedList(new ArrayList());运行结果还是上面的结果。
有点不明白了,有没有人解释一下?

解决方案 »

  1.   

    Vectors是可同步化的,意思就是说,任何操作Vector的内容的方法都是线程安全的,相反的,另一方面,ArrayList是不可同步化的,所以也不是线程安全的。如果你知道了这些的话,你就会发现,Vector的同步会让它在性能发方面有一些小问题。所以,如果你不需要线程安全的话,那么就使用ArrayList吧。为什么要为没有必要的同步付出代价呢?
      

  2.   

    有什么不明白,你这个ArrayList改不改成同步就不影响运行结果。
    你是想测试同步集合吗?你把List   l改成同步的集合不还是做一样的事吗?
    Thread线程的sleep方法确实不会释放对象锁,但是你的线程sleep的太短了、而且run内不是循环、一个线程迅速就执行完了。
    想测试同步集合或者同步线程你得改改代码。