使用Java ExecutorService,我如何完成主动执行的任务,但停止等待任务的处理?
我正在使用ExperidorService(ThreadPoolExecutor)来运行(和排队)很多任务。我正在尝试编写一些尽可能优雅的关闭代码。
ExecutorService 有两种关闭方式:
- 我可以打电话,然后.
ExecutorService.shutdown()
ExecutorService.awaitTermination(...)
- 我可以打电话给.
ExecutorService.shutdownNow()
根据 JavaDoc,该命令:shutdown
Initiates an orderly shutdown in which previously submitted
tasks are executed, but no new tasks will be accepted.
和命令:shutdownNow
Attempts to stop all actively executing tasks, halts the
processing of waiting tasks, and returns a list of the tasks that were
awaiting execution.
我想要在这两个选项之间找到一些东西。
我想调用一个命令:
a。完成当前活动的任务(如 )。
(二)停止处理等待的任务(如 )。shutdown
shutdownNow
例如:假设我有一个线程池执行器,有3个线程。它当前在队列中有 50 个任务,前 3 个任务正在运行。我想允许这3个活动任务完成,但我不希望剩余的47个任务开始。
我相信我可以通过这种方式关闭执行器服务,方法是保留一个对象列表,然后调用所有对象。但是,由于任务是从多个线程提交到此执行器服务的,因此没有一种干净的方法来执行此操作。Future
cancel
我真的希望我错过了一些明显的东西,或者有一种方法可以干净利落地做到这一点。
感谢您的任何帮助。