With a Java ExecutorService, how do I complete actively executing tasks but halt the processing of waiting tasks?

前端 未结 3 1074
清歌不尽
清歌不尽 2021-02-13 03:33

I am using an ExecutorService (a ThreadPoolExecutor) to run (and queue) a lot of tasks. I am attempting to write some shut down code that is as graceful as possible.

Exe

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-13 03:43

    The shutdownNow() is exactly what you need. You've missed the 1st word Attempts and the entire 2nd paragraph of its javadoc:

    There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via Thread.interrupt(), so any task that fails to respond to interrupts may never terminate.

    So, only tasks which are checking Thread#isInterrupted() on a regular basis (e.g. in a while (!Thread.currentThread().isInterrupted()) loop or something), will be terminated. But if you aren't checking on that in your task, it will still keep running.

提交回复
热议问题