第四章-证明ArrayList是线程不安全的

并发异常类

java.util.ConcurrentModificationException

解决方案1

  • new Vector<>()
  • Collections.sychronizedList(new ArrayList<>())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
* @desc 非线程安全容器
* 1.异常
* java.util.ConcurrentModificationException
* 2.解决方案
* 2.1 new Vector<>();
* 2.2 Collections.synchronizedList(new ArrayList<>());
* 2.3 new CopyOnWriteArrayList<>();
* @Author xw
* @Date 2019/8/20
*/
public class ContainerNotSafeDemo {
public static void main(String[] args) {
//listNotSafe();
//setNotSafe();
mapNotSafe();
}

private static void mapNotSafe() {
// Map<String, String> map = new HashMap<>();
// Map<String, String> map = Collections.synchronizedMap(new HashMap<>());
Map<String, String> map = new ConcurrentHashMap<>();
for (int i = 1; i <= 30; i++) {
new Thread(() -> {
map.put(Thread.currentThread().getName(), Thread.currentThread().getName());
System.out.println(map);
}, String.valueOf(i)).start();
}
}

private static void setNotSafe() {
//Set<String> list = new HashSet<>();
//Set<String> list = Collections.synchronizedSet(new HashSet<>());
Set<String> list = new CopyOnWriteArraySet<>();
for (int i = 1; i <= 30; i++) {
new Thread(() -> {
list.add(UUID.randomUUID().toString().substring(0, 8));
System.out.println(list);
}, String.valueOf(i)).start();
}
}

private static void listNotSafe() {
// List<String> list = new ArrayList<>();
// List<String> list = new Vector<>();
// List<String> list = Collections.synchronizedList(new ArrayList<>());
List<String> list = new CopyOnWriteArrayList<>();
for (int i = 1; i <= 30; i++) {
new Thread(() -> {
list.add(UUID.randomUUID().toString().substring(0, 8));
System.out.println(list);
}, String.valueOf(i)).start();
}
}
}

解决方案2

限制不能使用Vector和Collections工具类。

  • new CopyOnWriteList()
  • ReentrantLock

image-20191107103926727