arraylist和linkedlist 的 add(),remove(),iterator()在多线程访问下都需要加锁
vector容器的add() remove() 操作是thread-safe,但iterator不是thread-safe,多线程使用下需要先锁
CopyOnWriteArrayList,容器的 add,remove,itertor都是thread-safe。 因为调用 iterator的时候, 会返回一个 snapshot,所以其他线程只会修改容器本身而不会改动snapshot. .
HashMap 不是threadsafe, 多线程下可使用 java.util.concurrent.ConcurrentHashMap
关于copyonwriteArrayList的内部实现,可参考 https://www.cnblogs.com/dolphin0520/p/3938914.html
关于: Exception in thread "main" java.util.ConcurrentModificationException
以上代码会报错:Exception in thread "main" java.util.ConcurrentModificationException
原因在于list3 是list1的view. 如果list1修改了,会导致它的view(也就是list3)无效
list2.clear()会导致list1的修改 (把list1的前两个element删掉),因为这是一个Structural modifications,导致它的所有view无效.
如果有疑惑,可查看 https://docs.oracle.com/javase/7/docs/api/java/util/List.html#subList(int,%20int)
上面写道: sublist(fromIndex,toIndex ) Returns a view of the portion of this list between the specified from ndex, inclusive, and toIndex, exclusive. The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa. The returned list supports all of the optional list operations supported by this list.
The semantics of the list returned by this method become undefined if the backing list (i.e., this list) is structurally modified in any way other than via the returned list. (Structural modifications are those that change the size of this list, or otherwise perturb it in such a fashion that iterations in progress may yield incorrect results.)