多线程集合类
(1).不安全的list
单线程:
public class TestList {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
list.add(UUID.randomUUID().toString().substring(0,5));
System.out.println(list);
}
}
}
[cd205]
[cd205, d71ad]
[cd205, d71ad, 67e69]
[cd205, d71ad, 67e69, cf680]
[cd205, d71ad, 67e69, cf680, 085d8]
[cd205, d71ad, 67e69, cf680, 085d8, d12be]
[cd205, d71ad, 67e69, cf680, 085d8, d12be, 73923]
[cd205, d71ad, 67e69, cf680, 085d8, d12be, 73923, 84efb]
[cd205, d71ad, 67e69, cf680, 085d8, d12be, 73923, 84efb, cdfb6]
[cd205, d71ad, 67e69, cf680, 085d8, d12be, 73923, 84efb, cdfb6, 0efbe]
执行成功,且安全
多线程:
public class TestList {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
new Thread(()->{
list.add(UUID.randomUUID().toString().substring(0,5));
System.out.println(list);
}).start();
}
}
}
Exception in thread "Thread-4" [7267c, 13a6d, c8ac8, 6e2f8]
Exception in thread "Thread-3" Exception in thread "Thread-2"
[7267c, 13a6d, c8ac8, 6e2f8, 6a46f, 097b7, 324e4, a655e, 25ffb, 1f6ca]
[7267c, 13a6d, c8ac8, 6e2f8, 6a46f, 097b7, 324e4, a655e, 25ffb]
[7267c, 13a6d, c8ac8, 6e2f8, 6a46f, 097b7, 324e4, a655e]
[7267c, 13a6d, c8ac8, 6e2f8, 6a46f, 097b7]
[7267c, 13a6d, c8ac8, 6e2f8, 6a46f, 097b7, 324e4]
[7267c, 13a6d, c8ac8, 6e2f8, 6a46f]
java.util.ConcurrentModificationException //多线程错误
执行失败:java.util.ConcurrentModificationException
并发修改异常
解决方法->1:
改new ArrayList<>();
为new Vector<>();
是默认开启了synchronized
正因如此,效率低
public static void main(String[] args) {
List<String> list = new Vector<>();
for (int i = 0; i < 10; i++) {
new Thread(()->{
list.add(UUID.randomUUID().toString().substring(0