Executors线程池关闭时间计算
Executors线程池关闭时间计算
学习了:http://blog.csdn.net/wo541075754/article/details/51564359
https://www.cnblogs.com/stonefeng/p/5967451.html
http://blog.csdn.net/alinshen/article/details/78090043
shutdown方法:平滑的关闭ExecutorService,当此方法被调用时,ExecutorService停止接收新的任务并且等待已经提交的任务(包含提交正在执行和提交未执行)执行完成。当所有提交任务执行完毕,线程池即被关闭。 awaitTermination方法:接收人timeout和TimeUnit两个参数,用于设定超时时间及单位。当等待超过设定时间时,会监测ExecutorService是否已经关闭,若关闭则返回true,否则返回false。一般情况下会和shutdown方法组合使用。
代码:
package com.stono.thread; import java.util.concurrent.Callable; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class ExecutorShutdown { public static void main(String[] args) throws Exception { ScheduledExecutorService service = Executors.newScheduledThreadPool(4); for(int i=0;i<10;i++){ service.submit(new Task()); } service.submit(new LongTask()); service.shutdown(); while(!service.awaitTermination(1, TimeUnit.SECONDS)){ System.out.println("线程池没有关闭"); } System.out.println("线程池已经关闭============"); } } class Task implements Callable<Object>{ @Override public Object call() throws Exception { System.out.println("普通任务"); return null; } } class LongTask implements Callable<Object>{ @Override public Object call() throws Exception { System.out.println("长时间任务"); TimeUnit.SECONDS.sleep(15); return null; } }