0%

Java模拟并发场景

多线程环境下,我们要如何测试自己写的业务代码是否是线程安全的?

可以用到 CountDownLatch 这个类,让所有线程都 await, 然后 countDown 以后,所有线程共同执行。

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
62
63
64
65
66
67
68
69
70
71
72
73
74
package gy.finolo.concurrent;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


public class ConcurrentDemo {

// 线程数
private static final int WORKER_COUNT = 100;

// 竞争资源
private static int TOTAL = 100;

public static void main(String[] args) {

ExecutorService executorService = Executors.newCachedThreadPool();
CountDownLatch cdl = new CountDownLatch(1);

for (int i = 0; i < WORKER_COUNT; i++) {
Worker worker = new Worker(cdl);
executorService.execute(worker);
}

try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}

cdl.countDown();

try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
executorService.shutdown();
System.out.println("TOTAL should be ZERO, but it's : " + TOTAL);
}

static class Worker implements Runnable {

private CountDownLatch countDownLatch;

public Worker(CountDownLatch countDownLatch) {
this.countDownLatch = countDownLatch;
}

@Override
public void run() {
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}

this.executeTask();
}

// 需要并发处理的逻辑
private void executeTask() {
int a = TOTAL - 1;
try {
TimeUnit.MILLISECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
TOTAL = a;
}
}
}