简单说就是读写分离,读不加锁,增删改时加锁复制,线程安全;
写的效率比较低,相对Vector类读写都加锁,CopyOnWriteArrayList读的效率更高,适合读多写少,并且不要求实时一致性的使用场景。
方法有:
public boolean add(E e),public void add(int index, E element)
public E set(int index, E element),public E get(int index)
public E remove(int index),public boolean remove(Object o)
public boolean addIfAbsent(E e),public void clear()
public boolean containsAll(Collection<?> c),public boolean removeAll(Collection<?> c)
public List<E> subList(int fromIndex, int toIndex)
简单使用例子如下:
public class CopyAndWriteArrayListTest { public static void main(String[] args) { List<String> list = new CopyOnWriteArrayList<>(); Thread[] threads = new Thread[20]; for (int i=0; i<20; i++) { Runnable run = new Runnable() { @Override public void run() { for (int j=0; j<100; j++) { list.add("thread "+ j); } } }; threads[i] = new Thread(run); } long startTime = System.currentTimeMillis(); for (Thread thread : threads) { thread.start(); } for (Thread thread : threads) { try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } long endTime = System.currentTimeMillis(); System.out.println(endTime - startTime); } }