-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestMutex.java
More file actions
79 lines (56 loc) · 1.7 KB
/
TestMutex.java
File metadata and controls
79 lines (56 loc) · 1.7 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package com.chen.test;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
/**
* @author Chen WeiJie
* @date 2020-04-23 17:02:02
**/
public class TestMutex {
private static CyclicBarrier barrier = new CyclicBarrier(31);
private static int a = 0;
private static Mutex mutex = new Mutex();
public static void main(String[] args) throws BrokenBarrierException, InterruptedException {
for (int i = 0; i < 30; i++) {
new Thread(() -> {
for (int j = 0; j < 10000; j++) {
increment();
}
try {
barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
barrier.await();
System.out.println("a===" + a);
barrier.reset();
a = 0;
for (int i = 0; i < 30; i++) {
new Thread(() -> {
for (int j = 0; j < 10000; j++) {
increment2();
}
try {
barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
barrier.await();
System.out.println("a===" + a);
}
public static void increment() {
a++;
}
public static void increment2() {
mutex.lock();
a++;
mutex.unlock();
}
}