使用线程池时候当程序结束时候记得调用shutdown关闭线程池

3.10 使用线程池时候当程序结束时候记得调用shutdown关闭线程池

日常开发中为了便于线程的有效复用,线程池是经常会被用的工具,然而线程池使用完后如果不调用shutdown会导致线程池资源一直不会被释放。下面通过简单例子来说明该问题。

3.10.1问题复现

下面通过一个例子说明当不调用线程池对象的shutdown方法后,当线程池里面的任务执行完毕后主线程这个JVM不会退出。

public class TestShutDown {

        static void asynExecuteOne() {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.execute(new  Runnable() {
            public void run() {
                System.out.println("--async execute one ---");
            }
        });
    }
    
    static void asynExecuteTwo() {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.execute(new  Runnable() {
            public void run() {
                System.out.println("--async execute two ---");
            }
        });
    }
    

    public static void main(String[] args) {
       //(1)同步执行
        System.out.println("---sync execute---");
       //(2)异步执行操作one
        asynExecuteOne();
       //(3)异步执行操作two
        asynExecuteTwo();
       //(4)执行完毕
        System.out.println("---execute over---");
    }
}

如上代码主线程里面首先同步执行了操作(1)然后执行操作(2)(3),操作(2)(3)使用线程池的一个线程执行异步操作,我们期望当主线程和操操作(2)(3)执行完线程池里面的任务后整个JVM就会退出,但是执行结果却如下:

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论
这个错误通常是由于线程池关闭后,尝试提交新的任务导致的。在使用 `ThreadPoolExecutor` 时,需要显式地关闭线程池,否则会出现这个错误。 解决办法是在使用线程池后,调用 `shutdown()` 方法显式关闭线程池,避免在线程池已经关闭时尝试提交新的任务。 例如,在以下代码,如果没有显式关闭线程池,就会报错 `cannot schedule new futures after shutdown`: ```python import concurrent.futures def my_function(): print('Function started') time.sleep(1) print('Function finished') with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor: future1 = executor.submit(my_function) future2 = executor.submit(my_function) # 会报错:cannot schedule new futures after shutdown future3 = executor.submit(my_function) ``` 为了避免这个错误,可以使用以下代码: ```python import concurrent.futures def my_function(): print('Function started') time.sleep(1) print('Function finished') with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor: future1 = executor.submit(my_function) future2 = executor.submit(my_function) executor.shutdown() # 不会报错 future3 = executor.submit(my_function) ``` 在这个例子,我们首先使用 `with` 语句创建一个线程池,并使用 `executor.submit()` 方法提交两个任务。然后在使用线程池后,调用 `executor.shutdown()` 方法显式关闭线程池。这样即可避免报错 `cannot schedule new futures after shutdown`。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

加多

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值