当前位置: 首页 > news >正文

Java多种方法实现等待所有子线程完成再继续执行

简介

在现实世界中,我们常常需要等待其它任务完成,才能继续执行下一步。Java实现等待子线程完成再继续执行的方式很多。我们来一一查看一下。

Thread的join方法

该方法是Thread提供的方法,调用join()时,会阻塞主线程,等该Thread完成才会继续执行,代码如下:

private static void threadJoin() {List<Thread> threads = new ArrayList<>();for (int i = 0; i < NUM; i++) {Thread t = new Thread(new PkslowTask("Task " + i));t.start();threads.add(t);}threads.forEach(t -> {try {t.join();} catch (InterruptedException e) {throw new RuntimeException(e);}});System.out.println("threadJoin Finished All Tasks...");}

结果:

Task 6 is running
Task 9 is running
Task 3 is running
Task 4 is running
Task 7 is running
Task 0 is running
Task 2 is running
Task 1 is running
Task 5 is running
Task 8 is running
Task 1 is completed
Task 8 is completed
Task 6 is completed
Task 4 is completed
Task 3 is completed
Task 0 is completed
Task 7 is completed
Task 9 is completed
Task 2 is completed
Task 5 is completed
threadJoin Finished All Tasks...

CountDownLatch

CountDownLatch是一个很好用的并发工具,初始化时要指定线程数,如10。在子线程调用countDown()时计数减1。直到为0时,await()方法才不会阻塞。代码如下:

private static void countDownLatch() {CountDownLatch latch = new CountDownLatch(NUM);for (int i = 0; i < NUM; i++) {Thread t = new Thread(() -> {System.out.println("countDownLatch running...");try {Thread.sleep(1000);System.out.println("countDownLatch Finished...");latch.countDown();} catch (InterruptedException e) {throw new RuntimeException(e);}});t.start();}try {latch.await();} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println("countDownLatch Finished All Tasks...");
}

结果:

countDownLatch running...
countDownLatch running...
countDownLatch running...
countDownLatch running...
countDownLatch running...
countDownLatch running...
countDownLatch running...
countDownLatch running...
countDownLatch running...
countDownLatch running...
countDownLatch Finished...
countDownLatch Finished...
countDownLatch Finished...
countDownLatch Finished...
countDownLatch Finished...
countDownLatch Finished...
countDownLatch Finished...
countDownLatch Finished...
countDownLatch Finished...
countDownLatch Finished...
countDownLatch Finished All Tasks...

CyclicBarrier

CyclicBarrier与CountDownLatch类似,但CyclicBarrier可重置,可重用。代码如下:

private static void cyclicBarrier() {CyclicBarrier barrier = new CyclicBarrier(NUM + 1);for (int i = 0; i < NUM; i++) {Thread t = new Thread(() -> {System.out.println("cyclicBarrier running...");try {Thread.sleep(1000);System.out.println("cyclicBarrier Finished...");barrier.await();} catch (InterruptedException | BrokenBarrierException e) {throw new RuntimeException(e);}});t.start();}try {barrier.await();} catch (InterruptedException | BrokenBarrierException e) {throw new RuntimeException(e);}System.out.println("cyclicBarrier Finished All Tasks...");
}

结果:

cyclicBarrier running...
cyclicBarrier running...
cyclicBarrier running...
cyclicBarrier running...
cyclicBarrier running...
cyclicBarrier running...
cyclicBarrier running...
cyclicBarrier running...
cyclicBarrier running...
cyclicBarrier running...
cyclicBarrier Finished...
cyclicBarrier Finished...
cyclicBarrier Finished...
cyclicBarrier Finished...
cyclicBarrier Finished...
cyclicBarrier Finished...
cyclicBarrier Finished...
cyclicBarrier Finished...
cyclicBarrier Finished...
cyclicBarrier Finished...
cyclicBarrier Finished All Tasks...

executorService.isTerminated()

ExecutorService调用shutdown()方法后,可以通过方法isTerminated()来判断任务是否完成。代码如下:

private static void executeServiceIsTerminated() {ExecutorService executorService = Executors.newFixedThreadPool(THREADS);IntStream.range(0, NUM).forEach(i -> executorService.execute(new PkslowTask("Task " + i)));executorService.shutdown();while (!executorService.isTerminated()) {//waiting...}System.out.println("executeServiceIsTerminated Finished All Tasks...");}

结果:

Task 0 is running
Task 2 is running
Task 1 is running
Task 3 is running
Task 4 is running
Task 0 is completed
Task 2 is completed
Task 5 is running
Task 4 is completed
Task 7 is running
Task 3 is completed
Task 1 is completed
Task 8 is running
Task 6 is running
Task 9 is running
Task 5 is completed
Task 9 is completed
Task 7 is completed
Task 6 is completed
Task 8 is completed
executeServiceIsTerminated Finished All Tasks...

executorService.awaitTermination

executorService.awaitTermination方法会等待任务完成,并给一个超时时间,代码如下:

private static void executeServiceAwaitTermination() {ExecutorService executorService = Executors.newFixedThreadPool(THREADS);IntStream.range(0, NUM).forEach(i -> executorService.execute(new PkslowTask("Task " + i)));executorService.shutdown();try {if (!executorService.awaitTermination(1, TimeUnit.MINUTES)) {executorService.shutdownNow();}} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println("executeServiceAwaitTermination Finished All Tasks...");
}

结果:

Task 0 is running
Task 1 is running
Task 2 is running
Task 3 is running
Task 4 is running
Task 0 is completed
Task 5 is running
Task 1 is completed
Task 4 is completed
Task 7 is running
Task 3 is completed
Task 8 is running
Task 2 is completed
Task 9 is running
Task 6 is running
Task 5 is completed
Task 7 is completed
Task 9 is completed
Task 8 is completed
Task 6 is completed
executeServiceAwaitTermination Finished All Tasks...

executorService.invokeAll

使用invokeAll提交所有任务,代码如下:

private static void executeServiceInvokeAll() {ExecutorService executorService = Executors.newFixedThreadPool(THREADS);List<Callable<Void>> tasks = new ArrayList<>();IntStream.range(0, NUM).forEach(i -> tasks.add(new PkslowTask("Task " + i)));try {executorService.invokeAll(tasks);} catch (InterruptedException e) {throw new RuntimeException(e);}executorService.shutdown();System.out.println("executeServiceInvokeAll Finished All Tasks...");
}

结果:

Task 1 is running
Task 2 is running
Task 0 is running
Task 3 is running
Task 4 is running
Task 1 is completed
Task 3 is completed
Task 0 is completed
Task 2 is completed
Task 4 is completed
Task 8 is running
Task 5 is running
Task 6 is running
Task 9 is running
Task 7 is running
Task 8 is completed
Task 5 is completed
Task 6 is completed
Task 9 is completed
Task 7 is completed
executeServiceInvokeAll Finished All Tasks...

ExecutorCompletionService

ExecutorCompletionService通过take()方法,会返回最早完成的任务,代码如下:

private static void executorCompletionService() {ExecutorService executorService = Executors.newFixedThreadPool(10);CompletionService<String> service = new ExecutorCompletionService<>(executorService);List<Callable<String>> callables = new ArrayList<>();callables.add(new DelayedCallable(2000, "2000ms"));callables.add(new DelayedCallable(1500, "1500ms"));callables.add(new DelayedCallable(6000, "6000ms"));callables.add(new DelayedCallable(2500, "2500ms"));callables.add(new DelayedCallable(300, "300ms"));callables.add(new DelayedCallable(3000, "3000ms"));callables.add(new DelayedCallable(1100, "1100ms"));callables.add(new DelayedCallable(100, "100ms"));callables.add(new DelayedCallable(100, "100ms"));callables.add(new DelayedCallable(100, "100ms"));callables.forEach(service::submit);for (int i = 0; i < NUM; i++) {try {Future<String> future = service.take();System.out.println(future.get() + " task is completed");} catch (InterruptedException | ExecutionException e) {throw new RuntimeException(e);}}System.out.println("executorCompletionService Finished All Tasks...");executorService.shutdown();awaitTerminationAfterShutdown(executorService);
}

这里不同任务的时长是不一样的,但会先返回最早完成的任务:

2000ms is running
2500ms is running
300ms is running
1500ms is running
6000ms is running
3000ms is running
1100ms is running
100ms is running
100ms is running
100ms is running
100ms is completed
100ms is completed
100ms task is completed
100ms task is completed
100ms is completed
100ms task is completed
300ms is completed
300ms task is completed
1100ms is completed
1100ms task is completed
1500ms is completed
1500ms task is completed
2000ms is completed
2000ms task is completed
2500ms is completed
2500ms task is completed
3000ms is completed
3000ms task is completed
6000ms is completed
6000ms task is completed
executorCompletionService Finished All Tasks...

代码

代码请看GitHub: https://github.com/LarryDpk/pkslow-samples

相关文章:

Java多种方法实现等待所有子线程完成再继续执行

简介 在现实世界中&#xff0c;我们常常需要等待其它任务完成&#xff0c;才能继续执行下一步。Java实现等待子线程完成再继续执行的方式很多。我们来一一查看一下。 Thread的join方法 该方法是Thread提供的方法&#xff0c;调用join()时&#xff0c;会阻塞主线程&#xff0…...

制造企业数字化工厂建设步骤的建议

随着工业4.0、中国制造2025的深度推进&#xff0c;越来越多的制造企业开始迈入智能制造的领域&#xff0c;那数字工厂要从何入手呢&#xff1f; 数字工厂规划的核心&#xff0c;也正是信息域和物理域这两个维度&#xff0c;那就从这两个维度来进行分析&#xff0c;看如何进行数…...

网上鲜花交易平台,可运行

文章目录项目介绍一、项目功能介绍1、用户模块主要功能包括&#xff1a;2、商家模块主要功能包括&#xff1a;3、管理员模块主要功能包括&#xff1a;二、部分页面展示1、用户模块部分功能页面展示2、商家模块部分功能页面展示3、管理员模块部分功能页面展示三、部分源码四、底…...

【实战】用 Custom Hook + TS泛型实现 useArray

文章目录一、题目二、答案&#xff08;非标准&#xff09;三、关键知识点1.Custom Hook关键点案例useMountuseDebounce2.TS 泛型关键点一、题目 完善自定义 Hook —— useArray &#xff0c;使其能够完成 tryUseArray 组件中测试的功能&#xff1a; 入参&#xff1a;数组返回…...

【LeetCode】剑指 Offer(18)

目录 题目&#xff1a;剑指 Offer 35. 复杂链表的复制 - 力扣&#xff08;Leetcode&#xff09; 题目的接口&#xff1a; 解题思路&#xff1a; 代码&#xff1a; 过啦&#xff01;&#xff01;&#xff01; 写在最后&#xff1a; 题目&#xff1a;剑指 Offer 35. 复杂链…...

Kubernetes节点运行时从Docker切换到Containerd

由于k8s将于1.24版本弃用dockershim&#xff0c;所以最近在升级前把本地的k8s切换到了Containerd运行时&#xff0c;目前我的k8s版本是1.22.5&#xff0c;一个master&#xff0c;二个Node的配置&#xff0c;以下做为一个操作记录日志整理&#xff0c;其它可以参考官网文档。 在…...

【编程基础之Python】12、Python中的语句

【编程基础之Python】12、Python中的语句Python中的语句赋值语句条件语句循环语句for循环while循环continue语句break语句continue与break的区别函数语句pass语句异常处理语句结论Python中的语句 Python是一种高级编程语言&#xff0c;具有简单易学的语法&#xff0c;适用于各…...

android h5餐饮管理系统myeclipse开发mysql数据库编程服务端java计算机程序设计

一、源码特点 android h5餐饮管理系统是一套完善的WEBandroid设计系统&#xff0c;对理解JSP java&#xff0c;安卓app编程开发语言有帮助&#xff08;系统采用web服务端APP端 综合模式进行设计开发&#xff09;&#xff0c;系统具有完整的源代码和数据库&#xff0c;系统主要…...

容易混淆的嵌入式(Embedded)术语

因为做嵌入式开发工作虽然跳不出电子行业&#xff0c;但还是能接触到跨度较大的不同行当&#xff0c;身处不同的圈子。诸如医疗&#xff0c;银行&#xff0c;车载&#xff0c;工业&#xff1b;亦或者手机&#xff0c;PC&#xff0c;专用芯片&#xff1b;甚至可能横跨系统开发、…...

Nodejs 中 JSON 和 YAML 互相转换

JSON 转换成 YAML 1. 安装 js-yaml 库: npm install js-yaml2. 在程序中引入依赖库 const yaml require(js-yaml);3. 创建一个 js 对象, 代表 json 数据 const jsonData {name: John,age: 30,city: New York };4. 使用 yaml.dump() 把 js 对象转换成 YAML, 返回 YAML 字符…...

C++入门教程||C++ 修饰符类型||C++ 存储类

C 修饰符类型 C 允许在 char、int 和 double 数据类型前放置修饰符。修饰符用于改变基本类型的含义&#xff0c;所以它更能满足各种情境的需求。 下面列出了数据类型修饰符&#xff1a; signedunsignedlongshort 修饰符 signed、unsigned、long 和 short 可应用于整型&#…...

Android开发面试:Java知识答案精解

目录 Java 集合 集合概述 HashMap ConcurrentHashMap 泛型 反射 注解 IO流 异常、深浅拷贝与Java8新特性 Java异常 深浅拷贝 Java8新特性 并发 线程 线程池 锁 volatile JVM 内存区域 内存模型 类加载机制 垃圾回收机制 如何判断对象已死 Java 集合 …...

Windows上一款特别好用的画图软件

安装 废话不多说&#xff0c;打开windows的应用商店&#xff0c;搜索draw.io&#xff0c;点击获取即可。 画图 draw.io的布局左边是各种图形组件&#xff0c;中间是画布&#xff0c;右边是属性设置&#xff0c;文件扩展名是.drawio。 点击左边列表中的图形可以将它添加到画…...

html--学习

javascrapt交互&#xff0c;网页控制JavaScript&#xff1a;改变 HTML 图像本例会动态地改变 HTML <image> 的来源&#xff08;src&#xff09;&#xff1a;点亮灯泡<script>function changeImage() {elementdocument.getElementById(myimage) #内存变量&#xff0…...

关于递归处理,应该怎么处理,思路是什么?

其实问题很简单&#xff0c;就是想要循环遍历整个data对象&#xff0c;来实现所有name转成label&#xff0c;但是想到里面还有children属性&#xff0c;整个children里面可能还会嵌套很多很多的name&#xff0c;如此循环&#xff0c;很难搞&#xff0c;知道使用递归&#xff0c…...

重磅!牛客笔试客户端可防ChatGPT作弊

上线俩月&#xff0c;月活过亿。爆火的ChatGPT能代写文&#xff0c;撕代码&#xff0c;善玩梗&#xff0c;秒答题&#xff0c;几乎“无所不能”&#xff0c;争议也随之而来。调查显示&#xff0c;截至2023年1月&#xff0c;美国89%的大学生利用ChatGPT应付作业&#xff0c;53%的…...

春季训练营 | 前端+验证直通车-全实操项目实践,履历加成就业无忧

“芯动的offer”是2023年E课网联合企业全新推出集训培优班&#xff08;线下&#xff09;&#xff0c;针对有一定基础&#xff08;linux、verilog、uvm等&#xff09;在校学生以及想要通过短时间的学习进入到IC行业中的转行人士&#xff0c;由资深IC设计工程师带教&#xff0c;通…...

2.详解URL

文章目录视图函数1.1endpoint简介1.2 装饰器注册路由源码浅析1.3 另一种注册路由的方式---app.add_url_rule()1.4 视图函数中添加自定义装饰器2 视图类2.1 视图类的基本写法3 详细讲解注册路由的参数3.1常用的参数3.2不常用的参数(了解)视图函数 1.1endpoint简介 endpint参数…...

Android特别的数据结构(二)ArrayMap源码解析

1. 数据结构 public final class ArrayMap<K,V> implements Map<K,V> 由两个数组组成&#xff0c;一个int[] mHashes用来存放Key的hash值&#xff0c;一个Object[] mArrays用来连续存放成对的Key和ValuemHashes数组按非严格升序排列初始默认容量为0减容&#xff…...

减少if else

1. 三目运算符 可以理解为条件 ?结果1 : 结果2 里面的?号是格式要求。也可以理解为条件是否成立&#xff0c;条件成立为结果1&#xff0c;否则为结果2。 实例&#xff1a; public String handle(int code) {if (code 1) {return "success";} else {return &quo…...

铭豹扩展坞 USB转网口 突然无法识别解决方法

当 USB 转网口扩展坞在一台笔记本上无法识别,但在其他电脑上正常工作时,问题通常出在笔记本自身或其与扩展坞的兼容性上。以下是系统化的定位思路和排查步骤,帮助你快速找到故障原因: 背景: 一个M-pard(铭豹)扩展坞的网卡突然无法识别了,扩展出来的三个USB接口正常。…...

业务系统对接大模型的基础方案:架构设计与关键步骤

业务系统对接大模型&#xff1a;架构设计与关键步骤 在当今数字化转型的浪潮中&#xff0c;大语言模型&#xff08;LLM&#xff09;已成为企业提升业务效率和创新能力的关键技术之一。将大模型集成到业务系统中&#xff0c;不仅可以优化用户体验&#xff0c;还能为业务决策提供…...

51c自动驾驶~合集58

我自己的原文哦~ https://blog.51cto.com/whaosoft/13967107 #CCA-Attention 全局池化局部保留&#xff0c;CCA-Attention为LLM长文本建模带来突破性进展 琶洲实验室、华南理工大学联合推出关键上下文感知注意力机制&#xff08;CCA-Attention&#xff09;&#xff0c;…...

React第五十七节 Router中RouterProvider使用详解及注意事项

前言 在 React Router v6.4 中&#xff0c;RouterProvider 是一个核心组件&#xff0c;用于提供基于数据路由&#xff08;data routers&#xff09;的新型路由方案。 它替代了传统的 <BrowserRouter>&#xff0c;支持更强大的数据加载和操作功能&#xff08;如 loader 和…...

【力扣数据库知识手册笔记】索引

索引 索引的优缺点 优点1. 通过创建唯一性索引&#xff0c;可以保证数据库表中每一行数据的唯一性。2. 可以加快数据的检索速度&#xff08;创建索引的主要原因&#xff09;。3. 可以加速表和表之间的连接&#xff0c;实现数据的参考完整性。4. 可以在查询过程中&#xff0c;…...

STM32+rt-thread判断是否联网

一、根据NETDEV_FLAG_INTERNET_UP位判断 static bool is_conncected(void) {struct netdev *dev RT_NULL;dev netdev_get_first_by_flags(NETDEV_FLAG_INTERNET_UP);if (dev RT_NULL){printf("wait netdev internet up...");return false;}else{printf("loc…...

Qt Widget类解析与代码注释

#include "widget.h" #include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget) {ui->setupUi(this); }Widget::~Widget() {delete ui; }//解释这串代码&#xff0c;写上注释 当然可以&#xff01;这段代码是 Qt …...

从深圳崛起的“机器之眼”:赴港乐动机器人的万亿赛道赶考路

进入2025年以来&#xff0c;尽管围绕人形机器人、具身智能等机器人赛道的质疑声不断&#xff0c;但全球市场热度依然高涨&#xff0c;入局者持续增加。 以国内市场为例&#xff0c;天眼查专业版数据显示&#xff0c;截至5月底&#xff0c;我国现存在业、存续状态的机器人相关企…...

相机从app启动流程

一、流程框架图 二、具体流程分析 1、得到cameralist和对应的静态信息 目录如下: 重点代码分析: 启动相机前,先要通过getCameraIdList获取camera的个数以及id,然后可以通过getCameraCharacteristics获取对应id camera的capabilities(静态信息)进行一些openCamera前的…...

TRS收益互换:跨境资本流动的金融创新工具与系统化解决方案

一、TRS收益互换的本质与业务逻辑 &#xff08;一&#xff09;概念解析 TRS&#xff08;Total Return Swap&#xff09;收益互换是一种金融衍生工具&#xff0c;指交易双方约定在未来一定期限内&#xff0c;基于特定资产或指数的表现进行现金流交换的协议。其核心特征包括&am…...