ArrayList与Vector的线程安全
package com.cwc.util;import java.util.ArrayList;import java.util.Vector;/** * Copyright(c), 2011-2100 * <p>Cwc System * @description:Synchronized of Vector and ArrayList * @file name:com.cwc.util.SynchronizedCollection.java * @create:by author axis on Mar 2, 2011 5:53:52 PM * @since: JDK1.6u21 */public class SynchronizedCollection {@SuppressWarnings("unchecked")static ArrayList arrayList = new ArrayList(20);@SuppressWarnings("unchecked")static Vector vector = new Vector();public static void main(String[] args) {Thread threadOne = new Thread(){@SuppressWarnings("unchecked")public void run(){for (int i = 0; i < 10; i++) {arrayList.add(arrayList.size(),new Integer(i));vector.add(vector.size(),new Integer(i));try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}}}};Thread threadTwo= new Thread(){@SuppressWarnings("unchecked")public void run(){for (int i = 0; i < 10; i++) {arrayList.add(arrayList.size(),new Integer(i));vector.add(vector.size(),new Integer(i));try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}}}};try {threadOne.start();threadTwo.start();threadOne.join();threadTwo.join();System.out.println(arrayList);System.out.println(vector);} catch (InterruptedException e) {e.printStackTrace();}}}大家注意下面图片中的Null,它不一定每次出来:
http://dl.iteye.com/upload/picture/pic/82847/40ecb214-a847-3b99-b10c-400dc71cbc9d.jpg
页:
[1]