ArrayList的线程安全问题
代码
package com.mine.juc.collection;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class ArrayListDemo {
public static void main(String[] args) {
final List<String> list = new ArrayList<String>();
for (int i = 1; i <= 100; i++) {
new Thread(new Runnable() {
public void run() {
list.add(UUID.randomUUID().toString().substring(0, 10));
System.out.println(list);
}
}).start();
}
}
}
问题
Exception in thread "Thread-21" [e0ea16e2-d, 19f4d8ec-b, ef4f030d-c, 0224861c-c, e7683cba-3, b3a2f7b9-0, 8eb49864-4, c8664e88-e, 31b5e3ef-0, 51560422-a, 5436893c-a, 31b11696-8]Exception in thread "Thread-29" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
at java.util.AbstractCollection.toString(AbstractCollection.java:461)
解决方案:
- Vector
- Collections
- CopyOnWriteArrayList
代码
CopyOnWriteArrayList(Vector同)
package com.mine.juc.collection;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;
public class CopyOnWriteArrayListD