Skip to content

Commit 30f60c5

Browse files
committed
同步线程类:CoutDownLatch
1 parent 8d2be95 commit 30f60c5

1 file changed

Lines changed: 48 additions & 0 deletions

File tree

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package org.javacore.concurrent;
2+
3+
import java.util.Random;
4+
import java.util.concurrent.CountDownLatch;
5+
import java.util.concurrent.ExecutorService;
6+
import java.util.concurrent.Executors;
7+
import java.util.concurrent.TimeUnit;
8+
9+
/**
10+
* 同步辅助类:完成一组线程执行前,使得一个或多个线程一直等待
11+
*
12+
* Created by bysocket on 16/4/26.
13+
*/
14+
public class CountDownLatchT {
15+
16+
// 线程中止的计数器
17+
private final static int COUNT = 10;
18+
private final static CountDownLatch count = new CountDownLatch(COUNT);
19+
20+
// 线程池
21+
private final static ExecutorService service = Executors.newFixedThreadPool(5);
22+
23+
public static void main(String[] args) throws InterruptedException {
24+
for (int i = 0; i < COUNT; i++) {
25+
service.execute(() -> {
26+
try {
27+
int time = new Random().nextInt(5);
28+
TimeUnit.SECONDS.sleep(time);
29+
System.out.printf("Thread %s ## 耗时:%d\n", Thread.currentThread().getId(), time);
30+
// 线程结束后,计数器减一
31+
count.countDown();
32+
} catch (InterruptedException e) {
33+
e.printStackTrace();
34+
}
35+
36+
});
37+
}
38+
39+
// 主线程一直被阻塞,直到count为0,实现线程同步
40+
count.await();
41+
service.shutdown();
42+
43+
System.out.println("同步线程执行组结束!");
44+
45+
}
46+
}
47+
48+

0 commit comments

Comments
 (0)