停止ExcutorService线程池的方法

今天遇到一个需求是停止正在运行的线程池,所在研究了一下怎么停止ExcutorService

先上代码:

public class Excutor {
    private static int count = 0;
    public static void main(String []args){
        ExecutorService excutor = Executors.newCachedThreadPool();
        ExecutorService subExcutor = Executors.newCachedThreadPool();
            for(int i=0;i<5;i++){
                excutor.submit(()-> {
                    try{
                        count++;
                        System.out.printf("主线程");
                        if(!subExcutor.isShutdown()){
                            CountDownLatch countDownLatch = new CountDownLatch(100);
                            for(int j=0;j<5;j++){
                                subExcutor.submit(()->{
                                    try {
                                        count++;
                                        System.out.printf("子线程");
                                    }catch (Exception e){
                                        System.out.println("子线程"+e);
                                    }finally {
                                        countDownLatch.countDown();
                                    }
                                });
                            }
                            countDownLatch.await();
                        }
                    }catch (Exception e){
                        System.out.println("主线程"+e);
                    }
                });
        }
        excutor.shutdownNow();
        subExcutor.shutdownNow();
    }
}

停止线程池的方法有两种一种是

1、shutdown()方法在终止前允许执行以前提交的任务。 这个方法会顺次地关闭ExecutorService,当我们调用这个方法时,ExecutorService停止接受任何新的任务且等待已经提交的任务执行完成(已经提交的任务会分两类:一类是已经在执行的,另一类是还没有开始执行的),当所有已经提交的任务执行完毕后将会关闭ExecutorService。

 2、shutdownNow()方法则是阻止正在任务队列中等待任务的启动并试图停止当前正在执行的任务,返回要停止的任务List。

 List<Runnable> shutdownNow();

因为线程池的特性,调用这两个函数都会抛出RejectedExecutionException

因此需要在提交任务之前,用isShutdown()来做判断。

猜你喜欢

转载自blog.csdn.net/yshuoo/article/details/83277058