public class Test { //LinkedList线程不安全 //List<Integer>list=new LinkedList<Integer>(); //Vector线程安全 List<Integer> list=new Vector<Integer>(); public static void main(String[] args) { Test test=new Test(); ThreadA tA = test.new ThreadA(); ThreadB tB = test.new ThreadB(); tA.start(); tB.start(); try{ tA.join(); tB.join(); }catch(InterruptedException e){ e.printStackTrace(); } System.out.println("list size:"+test.list.size()); } class ThreadA extends Thread{ @Override public void run(){ super.run(); for(int i=0;i<100;i++){ list.add(i); } } } class ThreadB extends Thread{ @Override public void run(){ super.run(); for(int i=0;i<100;i++){ list.add(i); } } } }
在list是Linkedlist的时候,无论怎么运行结果都不会是200,单如果要是用Vector实例出来的list结果总会是200.