List<String> list = new ArrayList<>();
使用ArrayList對數據進行賦值,會出現不同線程爭搶同一資源造成寫入失敗問題,會拋出異常“ConcurrentModificationException”
List<String> list = new Vector<>();
List<String> list = Collections.synchronizedList(new ArrayList<>());
List<String> list = new CopyOnWriteArrayList();
#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();
}
}