1、线程池所有子线程运行完再执行主线程
shutdown方法:该方法会停止ExecutorService添加新的任务, 但是老任务还是会继续执行。
awaitTermination方法:该方法是阻塞的, 阻塞到所有任务都完成(必须在shutdown调用之后)或者超时. 如果executor在超时之前终止了, 那么返回true, 否则返回false.
注意, 如果不在awaitTermination前调用shutdown, 则即使在超时之前所有任务都已经完成, awaitTermination仍然会等待着, 而且最后一定返回false, 因为没有shutdown的调用不会使executor的状态变为terminated
总结:也就是说,等把所有的线程都扔到线程池之后,就调用shutdown方法,然后就再调用awaitTermination方法检测线程池的任务是否都完成了。一直在阻塞。
注意:shutdown之后不能提交新任务,之前提交的任务会继续执行,而且不能重启启动了,如果还想使用就只能再起一个了。
public List xx(Integer count) throws InterruptedException {ExecutorService threadPool = Executors.newFixedThreadPool(5);long begin = System.currentTimeMillis();for (int i = 1; i <=6 ; i++) {threadPool.execute(() -> {//执行业务。。。});}threadPool.shutdown();while (!threadPool.awaitTermination(1, TimeUnit.SECONDS)) {System.out.println("线程池没有关闭");}System.out.println("线程池已经关闭");long end = System.currentTimeMillis();long takeTime = end - begin;System.out.println("请求结束"+takeTime/1000);return objects;}
