当前位置:网站首页>用Future与CountDownLatch实现多线程执行多个异步任务,任务全部完成后返回结果
用Future与CountDownLatch实现多线程执行多个异步任务,任务全部完成后返回结果
2022-04-23 06:00:00 【0oIronhide】
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
/** * 用Future与CountDownLatch实现多线程执行多个异步任务,任务全部完成后返回结果 */
public class TestFuture {
public static void main(String[] args) {
TestFuture testFuture = new TestFuture();
// 初始为三个任务数
int taskCount = 3;
List<Future<String>> futures = new ArrayList<>(taskCount);
// CountDownLatch作为递减计数器,一个线程完成了一个任务,计数器减一,减为0时表示任务全部完成
CountDownLatch downLatch = new CountDownLatch(taskCount);
ExecutorService executorService = new ThreadPoolExecutor
(taskCount, 5, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10));
for (int i = 0; i < taskCount; i++) {
// 开启三个异步任务
Future<String> future = executorService.submit(testFuture.executeTask(i, downLatch));
futures.add(future);
}
System.out.println("do other things");
try {
// 在downLatch不为0时,主线程会在此阻塞
downLatch.await();
executorService.shutdown();
// 通过future获取结果
List<String> result = testFuture.getFutureResult(futures);
for (String s : result) {
System.out.println(s);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public Callable<String> executeTask(int i, CountDownLatch downLatch) {
return () -> {
Thread.sleep(i * 1000L);
downLatch.countDown();
return "Result " + Thread.currentThread().getName();
};
}
public List<String> getFutureResult(List<Future<String>> futures) {
List<String> result = new ArrayList<>(3);
for (Future<String> future : futures) {
if (future.isDone() && !future.isCancelled()) {
try {
result.add(future.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
return result;
}
}
版权声明
本文为[0oIronhide]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_38599840/article/details/120708245
边栏推荐
- Installing redis using a small leather panel in the window environment
- 最近编程中遇到的一些问题2021/9/8
- 压力测试工具 Jmeter
- TP5中的getField()方法变化,tp5获取单个字段值
- LeetCode刷题|368最大整除子集(动态规划)
- 柯里化实现函数连续调用计算累加和
- 【MySQL基础篇】启动选项、系统变量、状态变量
- tensorflow下载
- 【不积跬步无以至千里】Oracle应用导数Ora-01455报错处理
- 【代码解析(5)】Communication-Efficient Learning of Deep Networks from Decentralized Data
猜你喜欢
随机推荐
DNA reveals surprise ancestry of mysterious Chinese mummies
mysql密码过期的方法
The getfield () method in TP5 changes, and TP5 gets the value of a single field
The arithmetic square root of X in leetcode
Leetcode integer plus one
批量修改/批量更新数据库某一个字段的值
Usage of if conditional statements in SQL
Typescript (top)
Jenkins搭建与使用
Leak detection and vacancy filling (III)
Each traversal usage of tp6
SQL学习|复杂查询
【代码解析(2)】Communication-Efficient Learning of Deep Networks from Decentralized Data
SQL学习|窗口函数
tc ebpf 实践
2021-09-18
Curry realization of function continuous call calculation and accumulation
并发优化请求
Scientists say Australian plan to cull up to 10,000 wild horses doesn’t go far enough
Leak detection and vacancy filling (II)