转载

使用Java ExecutorService,如何完成主动执行的任务,但是暂停处理等待任务?

我正在使用ExecutorService(ThreadPoolExecutor)运行(并排队)很多任务.我试图写一些尽可能优雅的关闭代码.

ExecutorService有两种关闭方式:

>我可以调用ExecutorService.shutdown(),然后调用ExecutorService.awaitTermination(…).

>我可以调用ExecutorService.shutdownNow().

根据JavaDoc,关机命令:

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.

我想要这两个选项之间的东西.

我想调用一个命令:

一个.完成当前活动的任务或任务(如关闭).

湾停止等待任务的处理(如shutdownNow).

例如:假设我有一个具有3个线程的ThreadPoolExecutor.它目前在队列中有50个任务,前3个正在运行.我想允许这3个活动任务完成,但我不希望剩下的47个任务开始.

我相信我可以通过保留Future对象的列表,然后调用所有这些对象来关闭ExecutorService.但是由于任务正从多个线程提交给此ExecutorService,所以不会有一个干净的方式来执行此操作.

我真的希望我缺少一些明显的东西,或者有一种干净的做法.

感谢任何帮助.

我最近遇到这个问题.可能有一个更优雅的方法,但是我的解决方案是首先调用shutdown(),然后拉出ThreadPoolExecutor使用的BlockingQueue,并调用clear()(或者将其释放到另一个Collection进行存储).最后,调用awaitTermination()可以让线程池完成其板上的内容.

例如:

public static void shutdownPool(boolean awaitTermination) throws InterruptedException {

    //call shutdown to prevent new tasks from being submitted
    executor.shutdown();

    //get a reference to the Queue
    final BlockingQueue<Runnable> blockingQueue = executor.getQueue();

    //clear the Queue
    blockingQueue.clear();
    //or else copy its contents here with a while loop and remove()

    //wait for active tasks to be completed
    if (awaitTermination) {
        executor.awaitTermination(SHUTDOWN_TIMEOUT, TimeUnit.SECONDS);
    }
}

该方法将在引导类中使用引用执行程序包装ThreadPoolExecutor来实现.

ThreadPoolExecutor.getQueue() javadoc中注意以下几点很重要:

Access to the task queue is intended primarily for debugging and  monitoring. This queue may be in active use. Retrieving the task queue  does not prevent queued tasks from executing.

这突出了事实,即在您消除BlockingQueue时,可能会调用其他任务.但是,根据 that interface’s documentation ,所有BlockingQueue实现都是线程安全的,所以这不应该导致问题.

http://stackoverflow.com/questions/8158500/with-a-java-executorservice-how-do-i-complete-actively-executing-tasks-but-halt

原文  https://codeday.me/bug/20181015/290667.html
正文到此结束
Loading...