如何正确关闭ExecutorService?

时间:2017-02-15 17:18:45

标签: multithreading threadpool executorservice scheduledexecutorservice

我有ScheduledExecutorService scheduler scheduleAtFixRate一些任务。 每项任务都有一个ExecutorService executor = Executors.newFixedThreadPool(poolSize) 这些执行程序将执行子任务。我有一个调用scheduler.shutdown()scheduler.shutdownNow()

的关闭钩子
    scheduler.shutdown();

    try {
        scheduler.awaitTermination(threadTimeout, TimeUnit.MINUTES)
    } catch(InterruptedException e) {
        scheduler.shutdownNow();
    }
  1. 但是会关闭子任务中的所有线程吗?我的理解是,这样做只会向线程发送中断信号 但这取决于线程何时可以停止。
  2. 当我使用Ctrl + C终止我的程序时,有时我会看到(基于输出日志)我的关机钩子运行,有时我不会。 如何保证我的设置顺利关机?
  3. 是否有必要在每个任务中使用某种标志并在关闭时更改它以指示线程停止或调用scheduler.shutdown()是否足够?

0 个答案:

没有答案
相关问题