Skip to content

Commit a3dd800

Browse files
committed
Create CountDownLatchExample1.java
1 parent 3875c0c commit a3dd800

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package com.example.helloworld.controller;
2+
3+
import java.util.concurrent.CountDownLatch;
4+
import java.util.concurrent.ExecutorService;
5+
import java.util.concurrent.Executors;
6+
7+
/**
8+
* @author SnailClimb
9+
* @date 2018年10月1日
10+
* @Description: CountDownLatch 使用方法示例
11+
*/
12+
public class CountDownLatchExample1 {
13+
// 请求的数量
14+
private static final int threadCount = 550;
15+
16+
public static void main(String[] args) throws InterruptedException {
17+
// 创建一个具有固定线程数量的线程池对象(如果这里线程池的线程数量给太少的话你会发现执行的很慢)
18+
ExecutorService threadPool = Executors.newFixedThreadPool(300);
19+
final CountDownLatch countDownLatch = new CountDownLatch(threadCount);
20+
for (int i = 0; i < threadCount - 1; i++) {
21+
final int threadnum = i;
22+
threadPool.execute(() -> {// Lambda 表达式的运用
23+
try {
24+
test(threadnum);
25+
} catch (InterruptedException e) {
26+
// TODO Auto-generated catch block
27+
e.printStackTrace();
28+
} finally {
29+
countDownLatch.countDown();// 表示一个请求已经被完成
30+
}
31+
32+
});
33+
}
34+
countDownLatch.await();
35+
threadPool.shutdown();
36+
System.out.println("finish");
37+
}
38+
39+
public static void test(int threadnum) throws InterruptedException {
40+
Thread.sleep(1000);// 模拟请求的耗时操作
41+
System.out.println("threadnum:" + threadnum);
42+
Thread.sleep(1000);// 模拟请求的耗时操作
43+
}
44+
}

0 commit comments

Comments
 (0)