Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中使用ThreadPoolExecutor时,如何通过超时取消特定任务?_Java_Multithreading_Threadpoolexecutor - Fatal编程技术网

在Java中使用ThreadPoolExecutor时,如何通过超时取消特定任务?

在Java中使用ThreadPoolExecutor时,如何通过超时取消特定任务?,java,multithreading,threadpoolexecutor,Java,Multithreading,Threadpoolexecutor,我在Java中使用ThreadPoolExecutor来并行化项目处理。每个项目处理都是一个单独的任务,我将其放入一个队列中供执行者处理。不幸的是,有些任务可能会花费太长的时间,我希望能够取消这些任务并继续其余的任务。我不想等待shutdown方法及其超时(整个处理过程需要几天)。 我想要像循环当前执行的任务,检查它运行的时间,如果超过限制,则取消它。当您向ThreadPoolExecutor提交任务时,ThreadPoolExecutor将向您返回未来的对象 对未来使用此方法,如果您得到Tim

我在Java中使用ThreadPoolExecutor来并行化项目处理。每个项目处理都是一个单独的任务,我将其放入一个队列中供执行者处理。不幸的是,有些任务可能会花费太长的时间,我希望能够取消这些任务并继续其余的任务。我不想等待shutdown方法及其超时(整个处理过程需要几天)。
我想要像循环当前执行的任务,检查它运行的时间,如果超过限制,则取消它。

当您向ThreadPoolExecutor提交任务时,ThreadPoolExecutor将向您返回未来的对象


对未来使用此方法,如果您得到TimeoutException,则调用cancel。

您可以使用
FutureTask
包装您的
Runnable
。它有
cancel()
方法:请注意,如果调用
cancel(true)
Runnable
中的代码将在调用任何可能抛出它的方法时抛出
中断异常,例如,
sleep()
。您还可以按说明通过调用
thread.interrupted()
来检查线程是否被中断。让我补充一点,如果您不调用
thread.interrupted()
sleep()
或其他什么,您的代码不会因为是已取消任务的一部分而终止。@GiovanniBotta我同意。我没有详细讨论任务中断,因为这是另一个话题。