java多线程并发,如何等待所有线程完成

java-线程等待/同步的五种方法 在面试时,经常会有面试官问道,一个主线程有多个子线程,如何能使子线程的业务执行完成之后,再执行主线程业务逻辑。对于这个问题,本人能够想到的有五种方法,详细请移步源码 1、使用线程类自带的join方法,将子线程加入到主线程,在子线程执行完之后,在执行主线程逻辑。 例如 [java] view plain copy  print? publ 阅读详情

java多线程的实现方式很多,最简单的就是实现Runnable,然后new Thread了,例:

public class Async implements Runnable {
    @Override
    public void run() {
    }
}


public class MainClass {
    public void call(){
        for(int i=0;i<10;i++){
            Async async= new Async();
            Thread thread=new Thread(async);
            thread.start(); 
        }
}

但是如果需要这10个线程都跑完之后汇总他们的结果呢?这里可以加入CountDownLatch。

public class Async implements Runnable {
    private CountDownLatch countDownLatch;

    public void setCountDownLatch(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        //业务逻辑
        countDownLatch.countDown();
    }
}


public class MainClass {
    public void call(){
        int size=10;
        CountDownLatch ctl = new CountDownLatch(size);
        for(int i=0;i<size;i++){
            Async async= new Async();
            async.setCountDownLatch(ctl);
            Thread thread=new Thread(async);
            thread.start(); 
        }
        ctl.await(6, TimeUnit.SECONDS); //等待多久为超时
}

 

java高并发系列 - 第16天:JUC中等待多线程完成的工具类CountDownLatch,必备技能 CountDownLatch称之为闭锁,它可以使一个或一批线程在闭锁上等待,等到其他线程执行完相应操作后,闭锁打开,这些等待的线程才可以继续执行。确切的说,闭锁在内部维护了一个倒计数器。通过该计数器的值来决定闭锁的状态,从而决定是否允许等待的线程继续执行。常用方法:public CountDownLatch(int count):构造方法,count表示计数器的值,不能小于0,否者会报异常。 阅读详情

相关推荐

TIMER-XL:突破长上下文限制的Transformer时序预测新范式

本文深入解析了清华大学提出的TIMER-XL模型,这是一种突破长上下文限制的Transformer时序预测新范式。它采用Decoder-only架构与补丁级生成技术,并创新性地引入TimeAttention机制,有效解决了传统模型在处理海量历史数据时面临的“上下文瓶颈”问题,显著提升了长序列预测的精度与稳定性。

weixin_28340315的博客 445

java多线程怎么同步返回结果

在 Java 多线程中,如果需要等待线程执行完成并返回结果,可以使用 Java 的线程同步机制来实现。方法,会阻塞主线程,直到该线程执行完成。在被等待的线程执行完成后,可以通过返回值或者其他方式将结果返回给主线程。表示一个异步计算的结果,可以在主线程中等待线程的完成,并获取结果。可以让一个或多个线程等待其他线程完成某些操作后再执行。方法来等待线程执行完成。一个线程已经完成,然后在等待线程中使用。表示一个带有返回值的任务,可以使用。:可以使用 Java 的。方法:可以使用线程的。方法等待所有线程完成。

kkevin_zzhang的博客 4370

DBeaver 实战:手动配置 PostgreSQL JDBC 驱动的高级技巧

本文详细介绍了在DBeaver中手动配置PostgreSQL JDBC驱动的高级技巧。针对企业内网、多版本数据库兼容等场景,从获取官方驱动文件、创建自定义驱动配置,到使用Maven坐标管理、连接参数调优及解决常见连接问题,提供了完整的实战指南,帮助开发者实现对数据库连接环境的精准掌控。

apple5的专栏 836

JAVA在多线程下,主线程等待所有线程执行完毕

方式一登录后复制 ExecutorService taskExecutor = Executors.newFixedThreadPool(4); while(...) { taskExecutor.execute(new MyTask()); } taskExecutor.shutdown(); try { ta...

weixin_42298778的博客 315

ADRV9009学习资料保存:基于XC7Z100+ADRV9009的双收双发无线电射频板卡

ADRV9009学习资料保存:基于XC7Z100+ADRV9009的双收双发无线电射频板卡 一、板卡概述 基于XC7Z100+ADRV9009的双收双发无线电射频板卡是基于XilinxZYNQFPGA和ADI的无线收发芯片ADRV9009开发的专用功能板卡,用于5G小基站,无线图传,数据收发...

9361

YOLOv8n模型导出ONNX的避坑指南:解决版本差异,正确生成TensorRT/RKNN所需输出节点

本文详细介绍了YOLOv8n模型导出ONNX格式的实战避坑指南,涵盖版本差异处理、代码修改技巧及TensorRT/RKNN部署优化方案。针对不同推理框架需求,提供输出节点生成、动态轴处理和后处理划分等核心问题的解决方案,帮助开发者高效完成模型部署。

weixin_33247358的博客 357

Java 线程间通信机制(等待唤醒机制)

Java线程间通信机制(等待唤醒机制)

weixin_67658096的博客 1106

erdas监督分类(二)

去云 用一张没有云的影像替代有云影像 构建aoi图层 将云和云影编码合并 重编码工作 在监督分类做的差不多以后(纠正无误,无明显错误),就要对监督分类图像进行重编码和颜色调整。 在中选中Recode,对原来分类的地物类别进行重编码,(为彻底修改,记得备份)选中一列,在New Value输入新的编码,依次编码后点击应用apply,即可实现。 这时的图像如果是全黑的或者只有一两类的颜色也没有关系,新的编码覆盖掉了原来的编码,但是颜色并没有改变才会这样。可以点击图像,右击...

weixin_58968530的博客 958

Java:Async异步代码的实现方式

异步的八种实现方式。

彭世瑜的博客 2006

uniapp [全端兼容] - 详细实现用户电子签名 “逐字校验“ 将姓名按字拆开分别手写签署签字,把客户名字自动拆成单独的文字并由用户逐个依次签名与汉字笔画校验,支持汉字格、田字格、米字格、方格等!

uniapp,h5移动端网页,微信小程序,支付宝小程序,Android安卓,苹果ios,app,nvue,手写签名,电子签署,逐个字挨着写,写名字,将客户姓名分成单独的文字并依次手写,在田字格里写名字,米字格,方格,合同,书写轨迹,验证手写的文字是否正确,如何在uni-app做姓名拆分成独立的文字后手写每一个字,校验正确性,画板,汉字生成在米字格里并且让用户去写,如何画一个汉字田字格,vue把姓名拆分单独写签名,文字,拆掉,中文汉字网格,一个字一个字签名,一次只签名一个文字,判断签名的文字笔画是否正确,Un

🏆 前端领域优质创作者 1万+

【目标检测】基于yolov5的道路坑洼检测(附代码和数据集)

基于yolov5的道路坑洼检测(附代码和数据集)

学无止境、积少成多、厚积薄发 4620

java多线程 等待多个并发事件的完成

java API中提供了CountDownLatch类,它允许线程一直等待,知道等待操作结束。下面以一个视频会议等待人数为例。 1.视频会议类,实现Runnable接口。import java.util.concurrent.CountDownLatch;public class Videoconference implements Runnable { private final Cou

3702

【Altium designer】如何添加过孔阵列

按下图1指示,执行【Tool】菜单栏下【Via Stitching/Shielding】选项卡中的【Add Stitching to Net...】选项 图1 “添加过孔阵列”选项 点击【Add Stitching to Net...】选项后,会跳出一个窗口,让我们设置过孔阵列的参数信息,如下图2所示。 图2 过孔阵列参数设置 过孔阵列区域:勾选该选项框,即可绘制多边形区域; 过孔内径与焊盘直径:比如内径 【Hole Size】设为12mil,焊盘直径【Diameter】设为24mil; .

夜半少年的博客 2万+

java countdownlatch_并发工具类(一)等待多线程完成的CountDownLatch

简介CountDownLatch 允许一个或多个线程等待其他线程完成操作。应用场景假如有这样一个需求,当我们需要解析一个Excel里多个sheet的数据时,可以考虑使用多线程,每个线程解析一个sheet里的数据,等到所有的sheet都解析完之后,程序需要提示解析完成。在这个需求中,要实现主线程等待所有线程完成sheet的解析操作,最简单的做法是使用join。代码如下:public class Jo...

weixin_35867994的博客 280

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

java多线程 等待多个并发事件的完成【转】

来自:http://blog.youkuaiyun.com/qq_27603235/article/details/50651697 java API中提供了CountDownLatch类,它允许线程一直等待,知道等待操作结束。下面以一个视频会议等待人数为例。  1.视频会议类,实现Runnable接口。 import java.util.concurrent.CountDownLatch;

shareinfo2018 560

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

java高并发系列 - 第16天:JUC中等待多线程完成的工具类CountDownLatch,必备技

这是java高并发系列第16篇文章。 本篇内容 介绍CountDownLatch及使用场景 提供几个示例介绍CountDownLatch的使用 手写一个并行处理任务的工具类 假如有这样一个需求,当我们需要解析一个Excel里多个sheet的数据时,可以考虑使用多线程,每个线程解析一个sheet里的数据,等到所有的sheet都解析完之后,程序需要统计解析总耗时。分析一下:解析每个sheet耗时可...

239

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

[java并发]java高并发系列 - 第16天:JUC中等待多线程完成的工具类CountDownLatch,必备技能

原文链接:查看原文 感谢公众号“ 路人甲Java”的分享,如有冒犯,请联系删除,快去关注他吧 本篇内容: 介绍CountDownLatch及使用场景 提供几个示例介绍CountDownLatch的使用 手写一个并行处理任务的工具类 假如有这样一个需求,当我们需要解析一个Excel里多个sheet的数据时,可以考虑使用多线程,每个线程解析一个sheet里的数据,等到所有的sheet都解析完之后,程序需要统计解析总耗时。分析一下:解析每个sheet耗时可能不一样,总耗时就是最长耗时的那个操作。 我们

Aran_的博客 314

[Java并发]使用CountDownLatch和CyclicBarrier等待多线程完成

-

凤歌 465

Java多线程-并发工具类(二)等待多线程完成的CountDownLatch

参考:https://www.jianshu.com/p/1716ce690637http://ifeve.com/talk-concurrency-countdownlatch/CountDownLatch是什么CountDownLatch也叫闭锁,在JDK1.5被引入,允许一个或多个线程等待其他线程完成操作后再执行。CountDownLatch内部会维护一个初始值为线程数量的计数器,主线程执行...

earthhour的专栏 475

java.util.concurrent并发工具类:等待多线程完成的CountDownLatch

首先,介绍的是CountDownLatch是一个同步工具类。在java 1.5时引入 java.util.concurrent并发包,在java并发包中有三个类用于同步一批线程的行为,分别是CountDownLatch、Semaphore和CyclicBarrier;还有一些其它类比喻:ConcurrentMap、BlockingQueue等等。本次介绍CountDownLatch的用处及代码示例

_William_Cheung的博客 767

Java并发工具类(一):等待多线程完成的CountDownLatch

作用 CountDownLatch是一个同步工具类,它允许一个或多个线程一直等待,直到其他线程的操作执行完后再执行 简介 CountDownLatch是在java1.5被引入的,存在于java.util.concurrent包下,它允许1个或者多个线程一直等待,直到一组操作执行完成。 CountDownLatch是通过一个计数器来实现的,计数器的初始值为线程的数量,此值是线程将要等待的操作...

weixin_30677617的博客 103

java学习系列-高并发15:JUC中等待多线程完成的工具类CountDownLatch,必备技能

本节内容 介绍CountDownLatch及使用场景 提供几个示例介绍CountDownLatch的使用 手写一个并行处理任务的工具类 假如有这样一个需求,当我们需要解析一个Excel里多个sheet的数据时,可以考虑使用多线程,每个线程解析一个sheet里的数据,等到所有的sheet都解析完之后,程序需要统计解析总耗时。分析一下:解析每个sheet耗时可能不一样,总耗时就是最长耗时的那个操作。 我们能够想到的最简单的做法是使用join,代码如下: package com.itsoku.chat13;

星之宇的博客 256
上一篇: 在线播放m3u8和ts的方法
下一篇: mybatis操作mysql json
bly1126
博客等级 码龄18年 8粉丝 39原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值