Collections.synchronizedList使集合线程安全

    static List al = Collections.synchronizedList(new ArrayList(20));
    static Vector vt = new Vector();

    public static void main(String[] args) throws Exception {

        Thread thread1 = new Thread() {

            public void run() {
                for (int i = 0; i < 10; i++) {
                    al.add(new Integer(i));
                    vt.add(new Integer(i));
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        Thread thread2 = new Thread() {

            public void run() {
                for (int i = 0; i < 10; i++) {
                    al.add(new Integer(i));
                    vt.add(new Integer(i));
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        thread1.start();

        thread2.start();

        thread1.join();
        thread2.join();
        System.out.println(al);
        System.out.println(vt);
    }

 Collections.synchronizedList线程安全体现在对集合的操作上面。线程不安全时,当有2个线程同时对一个集合进行add操作,此时2个线程获取到的集合长度相同,然后当一个线程先插入后,另一个线程则不能add了。这是就会出现集合最终长度和预想的不一致,导致了线程不安全。

猜你喜欢

转载自wzw5433904.iteye.com/blog/2318807