---
title: "主线程里创建N个子线程，等待N个子线程全部执行完"
author: "113.com"
date: "2014-04-30T17:10:52Z"
tags: []
categories: ["编程语言"]
slug: "n-n"
draft: false
lastmod: "2014-04-30T17:10:52Z"
id: 2058953
url: "https://113-com.iteye.com/blog/2058953"
---

```
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);
	}
	
}
```