【并发编程】- 线程池使用shutdown()方法在运行的任务继续执行

130 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第18天,点击查看活动详情

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

调用shutdown()方法后,正在执行的任务和队列中的任务继续正常执行

线程实现代码如下:

public class ThirdRunnable implements Runnable {
    private String threadName;

    public ThirdRunnable(String threadName){
        super();
        this.threadName=threadName;
    }

    @Override
    public void run() {
        for (int i = 0; i < Integer.MAX_VALUE / 1000 ; i++) {
            Math.random();
            Math.random();
            Math.random();
        }
        System.out.println(Thread.currentThread().getName()+"任务完成!");
    }
}

运行类代码如下:

public class ShutdownListRun {
    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);
            threadPoolExecutor.shutdown();
            System.out.println("main 结束");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

运行结果如下:

pool-1-thread-1任务完成!
main 结束
pool-1-thread-2任务完成!
pool-1-thread-1任务完成!
pool-1-thread-2任务完成!

方法shutdown()的作用是使当前未执行完的线程继续执行,则不再添加新的任务Task,还有shutdown()方法不会阻塞,调用shutdown()方法后,主线程main就马上结束了,而线程池会继续运行知道所有任务执行完才会停止。如果不调用shutdown()方法,那么线程池会一直保持下去,以便随时执行被添加的新task任务。

调用shutdownNow()方法后队列中的任务被取消执行

线程执行代码如下:

public class ThirdRunnable implements Runnable {
    private String threadName;

    public ThirdRunnable(String threadName){
        super();
        this.threadName=threadName;
    }

    public String getThreadName(){
        return this.threadName;
    }

    @Override
    public void run() {
        for (int i = 0; i < Integer.MAX_VALUE / 1000 ; i++) {
            Math.random();
            Math.random();
            Math.random();
        }
        System.out.println(Thread.currentThread().getName()+"任务完成!");
    }
}