ThreadPoolExecutor 关闭

关闭ThreadPoolExecutor的API shutdown()和shutdownNow()区别

shutdown()

当线程池调用该方法时,线程池的状态则立刻变成SHUTDOWN状态。此时,则不能再往线程池中添加任何任务,否则将会抛出RejectedExecutionException异常。但是,此时线程池不会立刻退出,直到添加到线程池中的任务都已经处理完成,才会退出。

shutdownNow()

根据JDK文档描述,大致意思是:执行该方法,线程池的状态立刻变成STOP状态,并试图停止所有正在执行的线程,不再处理还在池队列中等待的任务,当然,它会返回那些未执行的任务。
它试图终止线程的方法是通过调用Thread.interrupt()方法来实现的,但是大家知道,这种方法的作用有限,如果线程中没有sleep 、wait、Condition、定时锁等应用, interrupt()方法是无法中断当前的线程的。所以,ShutdownNow()并不代表线程池就一定立即就能退出,它可能必须要等待所有正在执行的任务都执行完成了才能退出。

example

public class ThreadPoolExcutorTask {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = new ThreadPoolExecutor(10,20,30, TimeUnit.SECONDS,
                new ArrayBlockingQueue(10),r -> {
            Thread t = new Thread(r);
            return t;
        },new ThreadPoolExecutor.AbortPolicy());

        IntStream.range(0,20).boxed().forEach(i->{
            executorService.execute(() ->{
                try {
                    TimeUnit.SECONDS.sleep(10);
                    System.out.println(Thread.currentThread().getName()+" [ "+i+" ] finshed done");
                } catch (InterruptedException e) {
                    //e.printStackTrace();
                }
            });
        });

        // executorService.shutdown();
        List runnableList = null;
        try {
            runnableList = executorService.shutdownNow();
            System.out.println("====================over====================");
        }catch (Exception e){
            e.printStackTrace();
        }
//        executorService.awaitTermination(1,TimeUnit.HOURS);
        System.out.println(runnableList);
        System.out.println(runnableList.size());
        System.out.println("====================over====================");
    }
}

example

public class ThreadPoolExcutorTaskTimeOut {

    public static void main(String[] args) throws InterruptedException {

        ExecutorService executorService = new ThreadPoolExecutor(10,20,30, TimeUnit.SECONDS,
                new ArrayBlockingQueue(10), r -> {
            Thread t = new Thread(r);
            t.setDaemon(true);
            return t;
        },new ThreadPoolExecutor.AbortPolicy());


        IntStream.range(0,10).boxed().forEach(i->{
            executorService.submit(()->{
                while (true){}
            });
        });

        // executorService.shutdown();
        executorService.shutdownNow();
        executorService.awaitTermination(5,TimeUnit.SECONDS);
        System.out.println("====================over===================");

    }

}

你可能感兴趣的:(ThreadPoolExecutor 关闭)