-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountDownLatchTest2.java
More file actions
42 lines (35 loc) · 1.12 KB
/
Copy pathCountDownLatchTest2.java
File metadata and controls
42 lines (35 loc) · 1.12 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
package four;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CountDownLatchTest2 {
public static void main(String[] args) {
ExecutorService pool = Executors.newCachedThreadPool();
CountDownLatch cdl = new CountDownLatch(100);
for (int i = 0; i < 100; i++) {
CountRunnable runnable = new CountRunnable(cdl);
pool.execute(runnable);
}
pool.shutdown();
}
}
class CountRunnable implements Runnable {
private CountDownLatch countDownLatch;
public CountRunnable(CountDownLatch countDownLatch) {
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
// countDown 是原子的 但是 countDown 和 getCount 这个组合操作不是原子的
synchronized (countDownLatch) {
countDownLatch.countDown();
System.out.println("thread counts = " + (countDownLatch.getCount()));
}
try {
countDownLatch.await();
System.out.println("concurrency counts = " + (100 - countDownLatch.getCount()));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}