用Future与CountDownLatch实现多线程执行多个异步任务,任务全部完成后返回结果

2023-05-16

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;
    }
}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

用Future与CountDownLatch实现多线程执行多个异步任务,任务全部完成后返回结果 的相关文章

  • RK3399 9.0 Setting修改一级菜单和二级菜单

    RK3399 9 0 Setting去掉一级菜单以及网络下二级菜单 xff0c 留下以太网二级菜单 rk3399 9 span class token punctuation span span class token number 0 s
  • java.sql.SQLException: Expression #1 of ORDER BY clause is not in SELECT list, references column ‘me

    报错信息 xff1a The error may involve defaultParameterMap The error occurred while setting parameters SQL select distinct mas
  • 设计模式-生产者与消费者模式

    最近正在看C 43 43 日志的开源代码 xff0c 其中多个线程需要向文件中写入日志信息 xff0c 该将该算法逻辑抽象出来的话就是生产者与消费者设计模式 常见的生产者与消费者模式主要分为四类 xff1a 单生产者与单消费者模式 单生产者
  • 7月编程语言排行榜:Java第一,C#下滑到第六

    日前 xff0c TIOBE官网公布了7月编程语言指数排行榜 xff0c 前三名万年不变 xff0c 仍然是Java C C 43 43 先看一下前 20 名 前几名地位依旧稳固 xff0c 其中C还是以令人吃惊的速度 xff0c 持续大幅
  • java:synchronized 锁的原理

    synchronized 的基本认识 在多线程并发编程中 synchronized 一直是元老级角色 xff0c 很多人都会称呼它为重量级锁 但是 xff0c 随着 Java SE 1 6 对synchronized 进行了各种优化之后 x
  • sift = cv2.xfeatures2d.SIFT_create报错,解决

    本人原因opencv版本过高 xff0c 回退版本解决 先卸载原有opencv版本 pip uninstall opencv python pip uninstall opencv contrib python 回退版本到3 4 2 17解
  • CentOS 7.9上lightdm+ICEWM 桌面的配置+XManager远程

    IceWM是X Window系统的窗口管理器 IceWM的目标是速度 xff0c 简单 xff0c 并且不妨碍用户 它带有一个带寻呼机的任务栏 xff0c 全局键绑定和每窗口键绑定和动态菜单系统 应用程序窗口可以通过键盘和鼠标进行管理 窗口
  • windows下使用powershell 操作服务器进行上传或下载

    1 上传文件使用scp命令 43 本地路径 43 服务器用户名称 64 服务器Ip xff1a 上传路径 2 下载文件到本地 使用scp命令 43 服务器用户名称 64 服务器Ip xff1a 文件路径 43 下载到本地的路径 最后的点表示
  • 佛系解决 DataBinding 无法生成 Activity****Binding 类

    起初呢 xff0c ActivityMainBinding 该类始终无法生成 于是确定一下几个地方 build gradle android dataBinding enabled 61 true 布局文件名称 lt layout gt l
  • 宇宙最强pyqt5的安装(一)!!!

    前期准备工作 xff1a pythonIDE3 5以上版本开发环境pycharm编程知识熟悉python基本语法 在线安装pyqt5 安装sip C Users xxx gt pip install sip Collecting sip D
  • Win10下部署TensorFlow以及一些避坑小指南

    第一步 xff0c 下载Anaconda3 Anaconda官网目前最新的版本是Python3 6的 xff0c 想要历史版本的 xff0c 去下面的网站下载 xff1a https repo continuum io archive 我们
  • SpringBoot如何整合邮箱服务实现登录验证功能

    写在前面 这里主要讲解大致思路 详细代码 xff08 目前部分功能还在开发完善中 xff09 请见这里 如果个人用户还是想白嫖短信服务的话 xff0c 可以看看我的这篇博客 一 开启 POP3 SMTP服务 获得的授权码 这里以qq邮箱为例
  • 手动创建和挂载SWAP分区

    手动创建和挂载SWAP分区 在安装系统的时候很难决定多大的交换空间 xff0c 往往需要根据服务器实际负载 运行情况 以及未来可能应用来综合考虑 swap 分区的大小 xff0c 所以这里参考推荐最小 swap 大小更实际一些 xff1a
  • python中处理字符编码问题

    NO 1认识字符编码 GBK win默认中文字符编码是 xff1a GBK Unicode xff08 统一码 万国码 单一码 xff09 是计算机科学领域里的一项业界标准 xff0c 包括字符集 编码方案等 Unicode 是为了解决传统
  • python中if not的用法

    python中空的概念 xff1a 在python中 xff1a None False 0 空列表 空字典 空元祖 都相当于false coding utf 8 x 61 39 39 0 False None 1 x为真 故not x 为假
  • python实现文件上传下载的功能socket编程(基础版)

    环境介绍 xff1a 项目路径 xff1a 服务端执行过程 xff1a 客户端执行过程 xff1a 上传成功截图 xff1a 服务端代码 xff1a import socket file server 61 socket socket fi
  • -bash: java: command not found (Linux)

    原因 xff1a 安装jdk后没有配置环境变量 1 编辑配置文件 xff0c 配置环境变更 vim etc profile 在最下面添加 export JAVA HOME 61 usr local jdk8 export PATH 61 P
  • idea使用本地代码远程调试线上运行代码---windows环境

    场景 xff1a 今天在书上看了一个代码远程调试的方法 xff0c 自己本地验证了一下感觉十分不错 xff01 xff01 windows环境 xff1a 启动测试jar包 xff1a platform multiappcenter bas
  • anaconda:安装cuda和对应版本的cudnn

    复现别人论文的时候经常遇到不同的cuda版本 xff0c 可以使用anaconda创建虚拟环境 xff0c 并在不同的虚拟环境中配置对应的cuda版本 1 安装anaconda及虚拟环境使用 Anaconda多个python版本 xff08
  • Linux Server 种脚本自动执行

    在我们用python编写完脚本后 xff0c 时常需要定时运行我们的脚本 在这里 xff0c 我为大家介绍两种常用定时执行python脚本文件的方式 xff1a 第一种 xff1a crontab job 在Linux系统中可以通过设置cr

随机推荐