Java线程池,isShutDown、isTerminated的作用与区别
isShutDown当调用shutdown()或shutdownNow()方法后返回为true。
isTerminated当调用shutdown()方法后,并且所有提交的任务完成后返回为true;
isTerminated当调用shutdownNow()方法后,成功停止后返回为true;
如果线程池任务正常完成,都为false
import java.util.concurrent.Callable; public class ShortTask implements Callable { @Override public Object call() throws Exception { System.out.println("短任务"); return null; } }
import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; public class LongTask implements Callable { @Override public Object call() throws Exception { System.out.println("长任务"); TimeUnit.SECONDS.sleep(5); return null; } }
import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class Main { public static void main(String[] args) { ScheduledExecutorService service = Executors.newScheduledThreadPool(4); service.submit(new ShortTask()); service.submit(new ShortTask()); service.submit(new LongTask()); service.submit(new ShortTask()); System.out.println("isShutdown:" + service.isShutdown()); System.out.println("isTerminated:" + service.isTerminated()); service.shutdown(); // List<Runnable> list = service.shutdownNow(); // System.out.println(list.size()); System.out.println("isShutdown:" + service.isShutdown()); System.out.println("isTerminated:" + service.isTerminated()); try { while (!service.awaitTermination(1, TimeUnit.SECONDS)) { System.out.println("线程池没有关闭"); System.out.println("isTerminated:" + service.isTerminated()); } } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("线程池已经关闭"); System.out.println("isTerminated:" + service.isTerminated()); } }
/* 执行service.shutdown(); 短任务 短任务 长任务 短任务 isShutdown:false isTerminated:false isShutdown:true isTerminated:false 线程池没有关闭 isTerminated:false 线程池没有关闭 isTerminated:false 线程池没有关闭 isTerminated:false 线程池没有关闭 isTerminated:false 线程池已经关闭 isTerminated:true*/ /* 执行List<Runnable> list = service.shutdownNow(); System.out.println(list.size()); 短任务 短任务 长任务 isShutdown:false isTerminated:false 1 isShutdown:true isTerminated:false 线程池已经关闭 isTerminated:true */ /* 如果不执行shutdown,也不执行shutdownNow: 短任务 短任务 长任务 短任务 isShutdown:false isTerminated:false isShutdown:false isTerminated:false 线程池没有关闭 isTerminated:false 线程池没有关闭 isTerminated:false 线程池没有关闭 isTerminated:false 线程池没有关闭 isTerminated:false 线程池没有关闭 isTerminated:false 线程池没有关闭 isTerminated:false 线程池没有关闭 isTerminated:false 线程池没有关闭 isTerminated:false 线程池没有关闭 isTerminated:false ......一直这样输出 */
欢迎关注微信公众号:大数据从业者