主线程等待几个子线程执行完成方案
有时,为了程序的性能,我们有必要对程序中的for循环(含有sql/rpc操作)进行并发处理,要求是并发处理完之后才能继续执行主线程。现给出如下两种方案:
1. CountDownLatch
- package com.itlong.whatsmars.base.sync;
- import java.util.concurrent.CountDownLatch;
- /**
- * Created by shenhongxi on 2016/8/12.
- */
- public class CountDownLatchTest {
- public static void main(String[] args) {
- CountDownLatch latch = new CountDownLatch(3);
- long start = System.currentTimeMillis();
- for (int i = 0; i < 3; i++) {
- new Thread(new SubRunnable(i, latch)).start();
- }
- try {
- latch.await();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println(System.currentTimeMillis() - start);
- System.out.println("Main finished");
- }
- static class SubRunnable implements Runnable {
- private int id = -1;
- private CountDownLatch latch;
- SubRunnable(int id, CountDownLatch latch) {
- this.id = id;
- this.latch = latch;
- }
- @Override
- public void run() {
- try {
- Thread.sleep(3000);
- System.out.println(String
- .format("Sub Thread %d finished", id));
- } catch (InterruptedException e) {
- e.printStackTrace();
- } finally {
- latch.countDown();
- }
- }
- }
- }
CountDownLatch用队列来存放任务,主要是一个构造器和两个方法,相关代码这里不予赘述。CountDownLatch很贴合我们的要求,但没用到线程池,而且latch是只提供了计数功能然后子线程的逻辑有没有可能会在主线程逻辑之后执行??,综合考虑,我推荐下面的这种方案。
2. ExecutorService
- package com.itlong.whatsmars.base.sync;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.concurrent.Callable;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- /**
- * Created by shenhongxi on 2016/8/12.
- */
- public class CallableTest {
- public static void main(String[] args) throws Exception {
- ExecutorService pool = Executors.newFixedThreadPool(3);
- List<Callable<Void>> subs = new ArrayList<Callable<Void>>();
- for (int i = 0; i < 3; i++) {
- subs.add(new SubCallable(i));
- }
- long start = System.currentTimeMillis();
- try {
- pool.invokeAll(subs);
- } finally {
- pool.shutdown();
- }
- System.out.println(System.currentTimeMillis() - start);
- System.out.println("Main finished");
- }
- static class SubCallable implements Callable<Void> {
- private int id = -1;
- public SubCallable(int id) {
- this.id = id;
- }
- @Override
- public Void call() throws Exception {
- try {
- Thread.sleep(3000);
- System.out.println(String
- .format("Child Thread %d finished", id));
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- return null;
- }
- }
- }
AbstractExecutorService
- public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
- throws InterruptedException {
- if (tasks == null)
- throw new NullPointerException();
- List<Future<T>> futures = new ArrayList<Future<T>>(tasks.size());
- boolean done = false;
- try {
- for (Callable<T> t : tasks) {
- RunnableFuture<T> f = newTaskFor(t);
- futures.add(f);
- execute(f);
- }
- for (Future<T> f : futures) {
- if (!f.isDone()) {
- try {
- f.get();
- } catch (CancellationException ignore) {
- } catch (ExecutionException ignore) {
- }
- }
- }
- done = true;
- return futures;
- } finally {
- if (!done)
- for (Future<T> f : futures)
- f.cancel(true);
- }
- }
接下来我做了个join的试验,发现同样可以达到目的,但不推荐此法。
- package com.itlong.whatsmars.base.sync;
- /**
- * Created by shenhongxi on 2016/8/12.
- * 子线程与主线程是顺序执行的,各子线程之间还是异步的
- */
- public class JoinTest {
- public static void main(String[] args) throws Exception {
- Thread t1 = new Thread(new SubRunnable(0));
- Thread t2 = new Thread(new SubRunnable(1));
- Thread t3 = new Thread(new SubRunnable(2));
- long start = System.currentTimeMillis();
- t1.start();
- t2.start();
- t3.start();
- t1.join();
- t2.join();
- t3.join();
- System.out.println(System.currentTimeMillis() - start);
- System.out.println("Main finished");
- }
- static class SubRunnable implements Runnable {
- private int id = -1;
- SubRunnable(int id) {
- this.id = id;
- }
- @Override
- public void run() {
- try {
- System.out.println("hi, I'm id-" + id);
- Thread.sleep(9000);
- System.out.println(String
- .format("Sub Thread %d finished", id));
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- }
最后,我们顺便提下org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor
- public class ThreadPoolTaskExecutor extends ExecutorConfigurationSupport implements SchedulingTaskExecutor {
- private final Object poolSizeMonitor = new Object();
- private int corePoolSize = 1;
- private int maxPoolSize = Integer.MAX_VALUE;
- private int keepAliveSeconds = 60;
- private boolean allowCoreThreadTimeOut = false;
- private int queueCapacity = Integer.MAX_VALUE;
- private ThreadPoolExecutor threadPoolExecutor;
- /**
- * Set the ThreadPoolExecutor's core pool size.
- * Default is 1.
- * <p><b>This setting can be modified at runtime, for example through JMX.</b>
- */
- public void setCorePoolSize(int corePoolSize) {
- synchronized (this.poolSizeMonitor) {
- this.corePoolSize = corePoolSize;
- if (this.threadPoolExecutor != null) {
- this.threadPoolExecutor.setCorePoolSize(corePoolSize);
- }
- }
- }
- /**
- * Return the ThreadPoolExecutor's core pool size.
- */
- public int getCorePoolSize() {
- synchronized (this.poolSizeMonitor) {
- return this.corePoolSize;
- }
- }
看到我们熟悉的ThreadPoolExecutor之后,我们瞬间明白了一切。
另外我们脑补下几个接口/类的关系
- public interface ExecutorService extends Executor {
- <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
- throws InterruptedException;
- }
- public interface Executor {
- void execute(Runnable command);
- }
- public abstract class AbstractExecutorService implements ExecutorService{
- public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
- // ...
- }
- }
- public class ThreadPoolExecutor extends AbstractExecutorService {
- public ThreadPoolExecutor(int corePoolSize,
- int maximumPoolSize,
- long keepAliveTime,
- TimeUnit unit,
- BlockingQueue<Runnable> workQueue) {
- this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
- Executors.defaultThreadFactory(), defaultHandler);
- }
- }
原文链接:[http://wely.iteye.com/blog/2317944]
主线程等待几个子线程执行完成方案相关推荐
- Java多线程、主线程等待所有子线程执行完毕、共享资源
1.Java创建与启动线程 Java提供两种方式创建和启动线程:1.直接Thread类,2.实现Runable接口. 1.1 继承Thread类 public class myThread exte ...
- java主线程等待所有子线程执行完毕再执行
java主线程等待所有子线程执行完毕在执行,这个需求其实我们在工作中经常会用到,比如用户下单一个产品,后台会做一系列的处理,为了提高效率,每个处理都可以用一个线程来执行,所有处理完成了之后才会返回给用 ...
- Java主线程等待所有子线程执行完毕再执行解决办法(转)
方法一: Thread.join()方法,亲测可行,thread.join()方法 [java] view plain copy Vector<Thread> ts = new Vecto ...
- 主线程等待所有子线程结束的4种方法
目录 主线程不等待子线程全部结束 1.使用CountDownLatch 2.同步屏障CyclicBarrier 2.1.CyclicBarrier使用 2.2.CyclicBarrier复用 2.3. ...
- java 父线程_Java父线程(或是主线程)等待所有子线程退出的实例
导读热词 实例如下: static void testLock1(){ final AtomicInteger waitCount = new AtomicInteger(30000); final ...
- python 主程序等待 子线程_Python多线程中主线程等待所有子线程结束的方法
Python多线程中主线程等待所有子线程结束的方法 发布时间:2020-07-30 14:39:04 来源:亿速云 阅读:77 作者:小猪 这篇文章主要讲解了Python多线程中主线程等待所有子线程结 ...
- [Java][Android] 多线程同步-主线程等待全部子线程完毕案例
有时候我们会遇到这种问题:做一个大的事情能够被分解为做一系列相似的小的事情,而小的事情无非就是參数上有可能不同样而已! 此时,假设不使用线程,我们势必会浪费许多的时间来完毕整个大的事情.而使用线程的话 ...
- python主线程有两个子线程、创建两个主函数_Python多任务之线程
1.1. 线程 threading.Thread(target = 函数名) 线程的运行是没有先后顺序的 主线程死了,子线程必死.子线程结束后,子线程会给子线程收尸. 当调用Thread的时候,不会创 ...
- 面试官:如何让主线程等待所有的子线程执行结束之后再执行
java 主线程等待所有子线程执行完毕在执行,在工作总往往会遇到异步去执行某段逻辑, 然后先处理其他事情, 处理完后再把那段逻辑的处理结果进行汇总(比如用户下单一个产品,后台会做一系列的处理,为了提高 ...
最新文章
- 网络资源(9) - TDD视频
- 使用@functools.wraps的理由
- 服务间调用要通过网关吗_Asp.Net Boilerplate微服务实战(二)架构解析
- php网站点击按钮更新程序,php页面 点击按钮执行更新操作
- 1405 树的距离之和
- PERC5/6 RAID配置中文手册
- 变量不在选择列表中_Python3中的表达式运算符
- 我用 Python 集齐了支付宝五福!
- 电荷为什么不随运动而变化
- 【校招VIP】产品行测之逻辑推理
- matplotlib常用图形
- react兼容safari9_react项目兼容ie浏览器配置
- 团队管理,领导的“无为”就是最大“有为”
- 算法题_寻找最大连通区域
- Pubwin服务端重装(安装)教程
- 轻松学编曲,论FL钢琴卷帘
- EXCEL 删除表格内的空格和空白字符
- 【Zookeeper】ZK 是干什么的?
- native2ascii的使用技巧
- Google Map API 使用总结
热门文章
- HP OSPF 实验(多区域)
- python基础知识5——赋值与深浅拷贝——整数和字符串,列表元组字典
- 迁移到云端之前需要考虑哪些问题?
- mac terminal ssh client shuttle 免输密码
- 监控IIS的运行状态
- easy-excel导入导出excel(待完善)
- Sharepoint学习笔记---Debug--使用ULS Log跟踪Solution错误信息
- 统计局:去年12月天然气、电力生产增长较快
- Python高级知识点学习(一)
- 003——数组(三)count()reset()end()prev()next()current()