主线程里创建N个子线程,等待N个子线程全部执行完
2014-04-30 17:10
162 查看
1.主线程里创建N个子线程,等待N个子线程全部执行完后,打印每个子线程执行的时间。 import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * 主线程里创建N个子线程,等待N个子线程全部执行完后,打印每个子线程执行的时间。 * 一种可行的方法 */ public class MainThread { public static void main(String[] args) throws InterruptedException { int threadNum = 5; CountDownLatch latch = new CountDownLatch(threadNum); Map<String, Long> map = new ConcurrentHashMap<String, Long>(threadNum); ExecutorService pool = Executors.newFixedThreadPool(threadNum); for (int i=0; i < threadNum; i++) { pool.submit(new SubThread(latch, map)); } latch.await(); //计数减到0时一直等待 for (Map.Entry<String, Long> entry : map.entrySet()) { System.out.println(entry.getKey() + "执行耗时:" + entry.getValue() + "毫秒"); } pool.shutdown(); // Disable new tasks from being submitted try { // Wait a while for existing tasks to terminate if (!pool.awaitTermination(1, TimeUnit.SECONDS)) { pool.shutdownNow(); // Cancel currently executing tasks // Wait a while for tasks to respond to being cancelled if (!pool.awaitTermination(1, TimeUnit.SECONDS)) { System.err.println("Pool did not terminate"); } } } catch (InterruptedException ie) { // (Re-)Cancel if current thread also interrupted pool.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); } } } class SubThread implements Runnable { private CountDownLatch latch; private Map<String, Long> map; public SubThread(CountDownLatch latch, Map<String, Long> map) { this.latch = latch; this.map = map; } @Override public void run() { long start = System.currentTimeMillis(); System.out.println(Thread.currentThread() + "开始执行..."); try { Thread.sleep(1000); //模拟执行操作 latch.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } long end = System.currentTimeMillis(); System.out.println(Thread.currentThread() + "执行完毕"); map.put(Thread.currentThread().toString(), end-start); } }
阅读更多
相关文章推荐
- 线程创建,属性设置与获得,等待线程结束,线程中fork,以及执行exec()
- 控制台创建两个线程,等待一个线程的结束,执行另外一线程
- C# 多线程join的用法,等待多个子线程结束后再执行主线程
- 多个子线程并发执行,主线程等待所有子线程都结束后再继续运行
- Java并发:主线程等待多个子线程执行完才继续执行
- .Net最简单的创建多线程主线程等待所有线程执行完成的例子
- 进阶篇:等待多个子线程完毕再执行主线程的方法之CountDownLatch(十二)
- 主线程等待子线程全部执行完成
- Android异步通信机制简单地理解,Handler是当前线程的消息队列中的一个子队列,而Runable是可以被安排到Handler去运行的接口。 首先在Activity中创建一个继承自Han
- Android 创建线程执行任务
- 创建执行线程的方式三:实现 Callable 接口
- 在任意线程给Handler发送的消息为什么会在创建Handler的那个线程被执行?
- 异常信息:CLR无法从COM 上下文0x645e18 转换为COM上下文0x645f88,这种状态已持续60秒。拥有目标上下文/单元的线程很有可能执行的是非泵式等待或者在不发送 Windows 消息的
- 线程的创建、终止、等待
- java中对线程的实现 等待多个子线程结束 多个子线程运行中进行同步
- CLR 无法从 COM 上下文 0x1a2740 转换为 COM 上下文 0x1a28b0,这种状态已持续 60 秒。拥有目标上下文/单元的线程很有可能执行的是非泵式等待或者在不发送 Windows 消息的情况下处理一个运行时间非常长的操作
- java面试题:如何让三个子线程执行完,再执行主线程
- python 使用@run_on_executor 创建线程,后台执行并check(2)
- 多线程批量执行等待全部结果
- Linux 线程(创建/等待/终止)