/**
* @ClassName: NotSafeDemo
* @description:
* @author: XZQ
* @create: 2020/1/17 21:35
* 1、存在问题 java.util.ConcurrentModificationException
* 2、解决方案
* 1、Vector
* 2、Collections.synchronizedList(new ArrayList<>());
* 3、CopyOnWriteArrayList<>();写时复制
**/
public class NotSafeDemo {
public static void main(String[] args) {
// List<String> list = new ArrayList<>();//线程不安全
// List<String> list = Collections.synchronizedList(new ArrayList<>());
List<String> list = new CopyOnWriteArrayList<>();
for (int i = 0; i <20 ; i++) {
new Thread(()->{
list.add(UUID.randomUUID().toString().substring(8));
System.out.println(list);
},String.valueOf(i)).start();
}
}
}
一、 Vector
二、Collections.synchronizedList(new ArrayList<>());
三、CopyOnWriteArrayList<>();
CopyOnWriteArrayList是ArrayList的线程安全版本,从他的名字可以推测,CopyOnWriteArrayList是在有写操作的时候会copy一份数据,然后写完再设置成新的数据。CopyOnWriteArrayList适用于读多写少的并发场景。
源码:
/**
* {@inheritDoc}
*
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E get(int index) {
return elementAt(getArray(), index);
}
add方法:
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return {@code true} (as specified by {@link Collection#add})
*/
public boolean add(E e) {
synchronized (lock) {
Object[] es = getArray();
int len = es.length;
es = Arrays.copyOf(es, len + 1);
es[len] = e;
setArray(es);
return true;
}