原文出处:http://blog.chenlb.com/2008/12/main-thread-wait-all-sub-thread-finish-task-in-thread-pool.html
用线程池编写多线程程序时,当所有任务完成时,要做一些统计的工作。而统计工作必须要在所有任务完成才能做。所以要让主线程等待所有任务完成。可以使用ThreadPoolExecutor.awaitTermination(long timeout, TimeUnit unit)。请看示例代码:
- package com.chenlb;
-
- import java.util.Random;
- import java.util.concurrent.LinkedBlockingQueue;
- import java.util.concurrent.ThreadPoolExecutor;
- import java.util.concurrent.TimeUnit;
-
-
-
-
-
-
- public class ThreadPoolUse {
-
- public static class MyTask implements Runnable {
- private static int id = 0;
-
- private String name = "task-"+(++id);
- private int sleep;
-
- public MyTask(int sleep) {
- super();
- this.sleep = sleep;
- }
-
- public void run() {
- System.out.println(name+" -----start-----");
- try {
- Thread.sleep(sleep);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println(name+" -----end "+sleep+"-----");
- }
-
- }
-
- public static void main(String[] args) {
- System.out.println("==================start==================");
- ThreadPoolExecutor executor = new ThreadPoolExecutor(5,5, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
- int n = 10;
- int sleep = 10 * 1000;
- Random rm = new Random();
- for(int i=0; i<n; i++) {
- executor.execute(new MyTask(rm.nextInt(sleep)+1));
- }
-
- executor.shutdown();
-
- try {
- boolean loop = true;
- do {
- loop = !executor.awaitTermination(2, TimeUnit.SECONDS);
- } while(loop);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
-
- System.out.println("==================end====================");
- }
-
- }
当然还有其它方法。
分享到:
相关推荐
NULL 博文链接:https://zhaoningbo.iteye.com/blog/1158225
我在工作的过程中遇到一个问题,需要主线程等等所有子线程执行完后再做某件事情,在网上找了很多代码,都没有真正解决这个问题. 现在我解决了这个问题,把代码共享出来供大家参考. 代码中有注释和注意事项,相信大家看过...
JAVA主线程等待子线程执行完毕再执行[参照].pdf
Java多线程--让主线程等待所有子线程执行完毕
子线程任务发生异常,主线程事务如何回滚
主要介绍了Django异步任务线程池实现原理,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
在消息分发时,主线程的looper.loop()方法会遍历所有的消息进行分发,执行耗时任务。我们看下源码的loop()方法: for (;;) { Message msg = queue.next(); // might block if (msg == null) {
对于多线程而言,一个主要的难题就是如何线程是否都已经执行结束。 也就是说,需要在主线程开启子多线程后,直到子线程全部执行结束为止,回到主线程。
数据量很大百万条记录,因此考虑到要用多线程并发执行,在写的过程中又遇到问题,我想统计所有子进程执行完毕总共的耗时,在第一个子进程创建前记录当前时间用System.currentTimeMillis()在后一个子进程结束后...
Visual C++源代码 22 如何从子线程更新主线程数据Visual C++源代码 22 如何从子线程更新主线程数据Visual C++源代码 22 如何从子线程更新主线程数据Visual C++源代码 22 如何从子线程更新主线程数据Visual C++源代码...
子线程更新主线程数据(再谈多线程)
主线程等待子多线程(无结果返回)执行完成再继续执行
C#子线程刷新主线程示例源码 功能介绍: 使用线程操作 1、实时显示当前时间 2、输入加数和被加数,自动出现结果 技术特点: 使用了多线程实现了子线程刷新主线程 ,使用委托刷新主线程。 注意: 开发环境为...
我就废话不多说了,还是直接看代码吧! from time import ctime import threading import time def a(): #for i in range(5): print('Program a is running... at ', ctime(),u'.... time.sleep(0.2) ...
Unity异步线程调用主线程脚本程序,在Unity中异步线程调用主线程会报错,所以编写了一个Loom
python 零基础学习篇
java 子线程通过观察者模式通知主线程
非常实用不解释,用了才知道 个人收藏的一部分资料将陆续给大家上传
c#子线程如何读取及设置主线程ui的值,自己录的一个小视频,方便理解,比较菜鸟的方法,请勿喷!