-
Notifications
You must be signed in to change notification settings - Fork 7
/
HashMapExample1.java
61 lines (52 loc) · 1.66 KB
/
HashMapExample1.java
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
56
57
58
59
60
61
package com.will.highconcurrency.example.commonUnsafe;
import com.will.highconcurrency.annoations.NotThreadSafe;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
* Created by Will.Zhang on 2018/3/22 0022 17:09.
*/
@NotThreadSafe
public class HashMapExample1 {
//线程数
public static int clientTotal = 5000;
//并发数
public static int threadTotal = 200;
/*
hashMap是线程不安全的
*/
private static Map<Integer, Integer> map = new HashMap<>();
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newCachedThreadPool();
final Semaphore semaphore = new Semaphore(threadTotal);
final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
for (int i = 0; i < clientTotal; i++) {
final int count = i;
executorService.execute(() -> {
try {
semaphore.acquire();
update(count);
semaphore.release();
} catch (Exception e) {
e.printStackTrace();
}
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
System.out.println("hashMap size : " + map.size());
}
/**
* 往hashMap添加值
* @param i
*/
private static void update(int i){
map.put(i, i);
}
}