forked from DreamCats/java-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashSetTest.java
More file actions
54 lines (50 loc) · 1.47 KB
/
HashSetTest.java
File metadata and controls
54 lines (50 loc) · 1.47 KB
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
/**
* @program JavaBooks
* @description: HashSetTest
* @author: mf
* @create: 2020/02/14 17:21
*/
package com.juc.collectiontest;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;
public class HashSetTest {
public static void main(String[] args) {
// notSafe();
// safe1();
safe2();
}
/**
* 故障现象
* java.util.ConcurrentModificationException
*/
public static void notSafe() {
Set<String> list = new HashSet<>();
for (int i = 1; i <= 30; i++) {
new Thread(() -> {
list.add(UUID.randomUUID().toString().substring(0, 8));
System.out.println(list);
}, "Thread " + i).start();
}
}
public static void safe1() {
Set<String> list = Collections.synchronizedSet(new HashSet<>());
for (int i = 1; i <= 30; i++) {
new Thread(() -> {
list.add(UUID.randomUUID().toString().substring(0, 8));
System.out.println(list);
}, "Thread " + i).start();
}
}
public static void safe2() {
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);
}, "Thread " + i).start();
}
}
}