线程安全的ListJava中最常用的列表有:ArrayList和LinkedList,但这两个线程都不是线程安全的。在多线程的情况下,线程安全的ListVectorVector是在JDK1.0中加入的,由来已久;底层原理和ArrayList几乎一样,不同的是Vector的每个public方法都添加了synchronized保证并发安全,但是性能很低,不推荐使用Collections.synchronizedList()集合收集工具类提供了将List转换为线程安全的方法SynchronizedListpublicstaticListsynchronizedList(Listlist)的原理是在每个方法中加入synchronized,保证线程安全。相比Vector的可扩展性,更加灵活returnlist.set(index,element);}}publicvoidadd(intindex,Eelement){synchronized(mutex){list.add(index,element);}}publicEremove(intindex){synchronized(mutex){returnlist.remove(index);}}CopyOnWriteArrayList&CopyOnWriteArraySet使用写时复制(COW)实现线程安全的集合。好处是当有现成的修改时,还有其他线程可以读取。缺点是浪费空间。每增加或删除一个元素,都需要复制一个新的数组publicbooleanadd(Ee){synchronized(lock){//获取底层存储元素的数组Object[]es=getArray();//复制一份到es数组中intlen=es.length;es=Arrays.copyOf(es,len+1);//向末尾添加元素es[len]=e;//将变化复制回去setArray(es);返回真;}}