线程池(newFixedThreadPool)、子线程回应(CountDownLatch)
原文地址:http://blog.csdn.net/conquer0715/article/details/9000548 利用线程池newFixedThreadPool实现多线程,并通过CountDownLatch实现等待所有子线程结束后执行主线程。
//所有子线程执行完毕后执行主线程 static void threadsCall() { ExecutorService threadPool = Executors.newFixedThreadPool(10); int threadTaskNum = 5; final CountDownLatch answers = new CountDownLatch(threadTaskNum);//同步计数器 for (int i = 0; i < threadTaskNum; i++) { threadPool.execute(new Runnable() { @Override public void run() { try { System.out.println("线程" + Thread.currentThread().getName() + " 开始处理任务 ..."); Thread.sleep((long) (Math.random() * 5000)); System.out.println("线程" + Thread.currentThread().getName() + " 处理完毕,汇报结果!"); answers.countDown(); } catch (Exception e) {} } }); } threadPool.shutdown();// 线程池不再接受新任务,全部任务结束后保证线程池退出运行 try { answers.await();// 在所有子线程结束前保持阻塞 } catch (InterruptedException e) {} System.out.println("线程" + Thread.currentThread().getName() + "已收到所有汇报结果"); } 结果:
线程pool-1-thread-1 开始处理任务 ... 线程pool-1-thread-2 开始处理任务 ... 线程pool-1-thread-3 开始处理任务 ... 线程pool-1-thread-4 开始处理任务 ... 线程pool-1-thread-5 开始处理任务 ... 线程pool-1-thread-5 处理完毕,汇报结果! 线程pool-1-thread-2 处理完毕,汇报结果! 线程pool-1-thread-3 处理完毕,汇报结果! 线程pool-1-thread-1 处理完毕,汇报结果! 线程pool-1-thread-4 处理完毕,汇报结果! 线程main已收到所有汇报结果