主线程里创建N个子线程,等待N个子线程全部执行完

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值