优雅实现线程关闭

1、executorService.shutdown()关闭线程
1.1、线程任务
class TaskShutDownPool implements Runnable{
        @Override
        public void run() {
            try {
                Thread.sleep(5000);
                log.info("TaskShutDownPool:{}",Thread.currentThread().getName());
            } catch (InterruptedException e) {
                log.error("TaskShutDownPool.interrupted:{}",e.getMessage(),e);
            }
        }
    }
1.2、测试用例
 @Test
    public void testShutDown() throws InterruptedException {
        //创建线程实例
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 1000; i++) {
            //执行线程任务
            executorService.execute(new TaskShutDownPool());
        }
        Thread.sleep(1000);
        log.info("testShutDown.status:{},before",executorService.isShutdown());
        //关闭线程
        executorService.shutdown();
        log.info("testShutDown.status:{},before",executorService.isShutdown());
        Thread.sleep(500);
        log.info("testShutDown.shutDown");
        executorService.execute(new TaskShutDownPool());

    }
1.3、日志

调用executorService.shutdown()关闭线程之前,我们线程正常执行,

调用之后,线程此时是关闭的,但是已提交的线程不会立即关闭

这里表示,没有执行完的线程可以继续执行,但是行提交的线程则不允许提交。

2、executorService.isTerminated()关闭线程
2.1、测试用例
 //创建线程实例
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 1000; i++) {
            //执行线程任务
            executorService.execute(new TaskShutDownPool());
        }
        Thread.sleep(1000);
        log.info("testShutDown.status:{},before",executorService.isTerminated());
        //关闭线程
        executorService.isTerminated();
        log.info("testShutDown.status:{},after",executorService.isTerminated());
        Thread.sleep(500);
        log.info("testShutDown.isTerminated");
        executorService.execute(new TaskShutDownPool());
2.2、日志

日志false表示线程没有完全结束。

3、executorService.shutdownNow()线程关闭

立即关闭安线程

4、优雅关闭线程案例

@Slf4j
public class ThreadPoolUtils {

    private  ThreadPoolUtils(){}

    public static void shutDownPool(ExecutorService pool, int shutDownTimeout
        , int shutDownNowTimeout, TimeUnit timeUnit){

        pool.shutdown();
        try {
            if (!pool.awaitTermination(shutDownTimeout,timeUnit)){
                pool.shutdownNow();
                if (pool.awaitTermination(shutDownNowTimeout,timeUnit)){
                    log.error("ThreadPoolUtils.shutDownPool.error");
                }
            }
        } catch (InterruptedException e) {
            log.error("ThreadPoolUtils.shutDownPool.interrupt.error:{}",e.getMessage(),e);
            pool.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }

}

感谢小伙伴观看!可以把你的意见留在评论区。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值