List區(qū)別
-
CopyOnWriteArrayList
原理:在添加/修改時辛块,先對當(dāng)前容器復(fù)制一份,然后新的容器里添加元素,添加完元素之后,再將原容器的引用指向新的容器
*寫的速度特別慢机断,但是讀的速度特別快,同時又是線程安全
/** * 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(); } }
ArrayList
*線程不安全绣夺,但是效率高-
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; }
源碼:github 歡迎各位同學(xué)指出問題/建議