ArrayList是线程不安全的,在多线程下同时操作一个线程会出java.util.ConcurrentModificationException异常(并发修改异常),如下所示:
public static void main(String[] args) throws IOException { List<String> list = new ArrayList<>(); for (int i = 0; i < 30; i++) { new Thread(() -> { list.add(UUID.randomUUID().toString().substring(0, 8)); System.out.println(list); }, "thread" + i).start(); } }
解决办法:① 、使用List<String> list = new Vector<>();
②、 使用List<String> list = Collections.synchronizedList(new ArrayList<>());
③、 使用List<String> list = new CopyOnWriteArrayList<>();
Vector线程安全原因:
/** * Appends the specified element to the end of this Vector. * * @param e element to be appended to this Vector * @return {@code true} (as specified by {@link Collection#add}) * @since 1.2 */ public synchronized boolean add(E e) { modCount++; ensureCapacityHelper(elementCount + 1); elementData[elementCount++] = e; return true; }
CopyOnWriteArrayList线程安全原因:
/** * 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) { final ReentrantLock lock = this.lock; lock.lock(); try { Object[] elements = getArray(); int len = elements.length; Object[] newElements = Arrays.copyOf(elements, len + 1); newElements[len] = e; setArray(newElements); return true; } finally { lock.unlock(); } }
Vector
原文:https://www.cnblogs.com/zblwyj/p/13426900.html