Skip to content

Commit d86e658

Browse files
committed
🔖 并发容器示例
1 parent d481861 commit d86e658

2 files changed

Lines changed: 100 additions & 0 deletions

File tree

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package io.github.dunwu.javase.concurrent.collection;
2+
3+
import java.util.Map;
4+
import java.util.concurrent.ConcurrentHashMap;
5+
6+
/**
7+
* ConcurrentHashMap 示例
8+
* @author Zhang Peng
9+
* @date 2018/5/16
10+
*/
11+
public class ConcurrentHashMapDemo {
12+
13+
public static void main(String[] args) throws InterruptedException {
14+
15+
// HashMap 在并发迭代访问时会抛出 ConcurrentModificationException 异常
16+
// Map<Integer, Character> map = new HashMap<>();
17+
Map<Integer, Character> map = new ConcurrentHashMap<>();
18+
19+
Thread wthread = new Thread(() -> {
20+
System.out.println("写操作线程开始执行");
21+
for (int i = 0; i < 26; i++) {
22+
map.put(i, (char) ('a' + i));
23+
}
24+
});
25+
Thread rthread = new Thread(() -> {
26+
System.out.println("读操作线程开始执行");
27+
for (Integer key : map.keySet()) {
28+
System.out.println(key + " - " + map.get(key));
29+
}
30+
});
31+
wthread.start();
32+
rthread.start();
33+
Thread.sleep(1000);
34+
}
35+
}
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package io.github.dunwu.javase.concurrent.collection;
2+
3+
import java.util.List;
4+
import java.util.concurrent.CopyOnWriteArrayList;
5+
import java.util.concurrent.ExecutorService;
6+
import java.util.concurrent.Executors;
7+
8+
/**
9+
* CopyOnWriteArrayList 示例
10+
* @author Zhang Peng
11+
* @date 2018/5/16
12+
*/
13+
public class CopyOnWriteArrayListDemo {
14+
15+
static class ReadTask implements Runnable {
16+
17+
List<String> list;
18+
19+
ReadTask(List<String> list) {
20+
this.list = list;
21+
}
22+
23+
public void run() {
24+
for (String str : list) {
25+
System.out.println(str);
26+
}
27+
}
28+
}
29+
30+
static class WriteTask implements Runnable {
31+
32+
List<String> list;
33+
int index;
34+
35+
WriteTask(List<String> list, int index) {
36+
this.list = list;
37+
this.index = index;
38+
}
39+
40+
public void run() {
41+
list.remove(index);
42+
list.add(index, "write_" + index);
43+
}
44+
}
45+
46+
public void run() {
47+
final int NUM = 10;
48+
// ArrayList 在并发迭代访问时会抛出 ConcurrentModificationException 异常
49+
// List<String> list = new ArrayList<>();
50+
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
51+
for (int i = 0; i < NUM; i++) {
52+
list.add("main_" + i);
53+
}
54+
ExecutorService executorService = Executors.newFixedThreadPool(NUM);
55+
for (int i = 0; i < NUM; i++) {
56+
executorService.execute(new ReadTask(list));
57+
executorService.execute(new WriteTask(list, i));
58+
}
59+
executorService.shutdown();
60+
}
61+
62+
public static void main(String[] args) {
63+
new CopyOnWriteArrayListDemo().run();
64+
}
65+
}

0 commit comments

Comments
 (0)