shutdown和shutdownNow有什么不同?

演示shutdown效果的示例代码:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


public class Shutdown{
    //由于只是为了测试下效果,所以随便搞个线程池来搭配,生产建议手动创建线程池
    static ExecutorService executorService = Executors.newCachedThreadPool();

    static class Task implements Runnable {
        @Override
        public void run() {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "运行任务");
        }
    }

    public static void main(String[] args) throws Exception {
        for (int i = 0; i < 100; i++) {
            executorService.execute(new Task());
        }
        //加几个睡眠时间,方便看到效果
        TimeUnit.SECONDS.sleep(1);
        System.out.println("准备用shutdown方法关闭线程池");
        executorService.shutdownNow();
        System.out.println("线程池调用了shutdown方法");
        TimeUnit.SECONDS.sleep(1);
        System.out.println("继续向线程池提交一个任务");
        executorService.execute(new Task());
    }
}

运行结果:

  • 准备调用shutdown方法关闭线程池
    在这里插入图片描述

  • 调用了shutdown方法后,发现之前提交的任务还是会被执行
    在这里插入图片描述

  • 但是提交新的任务就会被拒绝
    在这里插入图片描述

演示shutdown效果的示例代码:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ShutdownNow{
    //由于只是为了测试下效果,所以随便搞个线程池来搭配,生产建议手动创建线程池
    static ExecutorService executorService = Executors.newCachedThreadPool();

    static class Task implements Runnable {
        @Override
        public void run() {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "运行任务");
        }
    }

    public static void main(String[] args) throws Exception {
        for (int i = 0; i < 100; i++) {
            executorService.execute(new Task());
        }
        TimeUnit.SECONDS.sleep(1);
        System.out.println("准备用shutdown方法关闭线程池");
        executorService.shutdownNow();
        System.out.println("线程池调用了shutdown方法");
        TimeUnit.SECONDS.sleep(1);
        System.out.println("继续向线程池提交一个任务");
        executorService.execute(new Task());
    }
}

运行结果:

  • 通过下面一张图就能够清晰的知道,在线程池调用了shutdownNow方法后,之前提交待运行的任务不会再执行,新任务提交也一样会被拒绝。

在这里插入图片描述

总结

线程池调用了shutdown方法,只是拒绝新任务的提交,那些已经存放在等待队列待执行的任务一样会被执行,而shutdownNow方法则不同,一旦调用后,线程池就立即关闭了,等待队列的任务不会再被执行,新任务的提交也会被拒绝。

原创文章 358 获赞 387 访问量 7万+

猜你喜欢

转载自blog.csdn.net/weixin_38106322/article/details/105761654