持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第19天,点击查看活动详情
接着上一篇文章【并发编程】- 线程池使用shutdown()方法在运行的任务继续执行
调用shutdownNow()方法后队列中的任务被取消执行
shutdownNow()方法是使线程池的状态立即变成STOP状态,并试图停止所有正在执行的线程,不再处理还在池队列中等待的任务,线程池会返回那些未执行的任务。
修改实现类代码如下:
public class ShutdownNowRun {
public static void main(String[] args) {
ThirdRunnable t1 = new ThirdRunnable("1");
ThirdRunnable t2 = new ThirdRunnable("2");
ThirdRunnable t3 = new ThirdRunnable("3");
ThirdRunnable t4 = new ThirdRunnable("4");
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 6, 999, TimeUnit.SECONDS,new LinkedBlockingQueue<>());
threadPoolExecutor.execute(t1);
threadPoolExecutor.execute(t2);
threadPoolExecutor.execute(t3);
threadPoolExecutor.execute(t4);
try {
Thread.sleep(1000);
List<Runnable> runnableList = threadPoolExecutor.shutdownNow();
for (int i = 0; i < runnableList.size() ; i++) {
ThirdRunnable runnable = (ThirdRunnable)runnableList.get(i);
System.out.println(runnable.getThreadName() +"任务被取消!");
}
System.out.println("main 结束");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
运行结果如下:
3任务被取消!
4任务被取消!
main 结束
pool-1-thread-2任务完成!
pool-1-thread-1任务完成!
调用shutdownNow()方法后队列中的任务被取消执行,方法shutdownNow()的返回值是List,List对象存储的是还未运行的任务,就是被取消掉的任务。
使用isShutdown()监听线程池是否关闭状态
public class IsShutdownRun {
public static void main(String[] args) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
System.out.println("执行开始时间"+simpleDateFormat.format(new Date()));
Thread.sleep(1000);
System.out.println("结束开始时间"+simpleDateFormat.format(new Date()));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 2, 999, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
threadPoolExecutor.execute(runnable);
System.out.println("第一阶段:"+threadPoolExecutor.isShutdown());
threadPoolExecutor.shutdown();
System.out.println("第二阶段:"+threadPoolExecutor.isShutdown());
}
运行结果如下:
第一阶段:false
第二阶段:true
执行开始时间14:23:36
结束开始时间14:23:37
从运行结果看出只要调用了shutdown()方法,isShutdown()方法的返回值是true。所以isShutdown()的作用是判断线程池的关闭状态。