在执行程序服务中实现线程超时

所以现在我有一个相当基本的Executor服务,用于将我的程序分解为线程,如下所示:

ExecutorService threadPool = Executors.newFixedThreadPool(12); for (int i = 0; i < objectArray.length; i++) { threadPool.submit(new ThreadHandler(objectArray[i], i)); // The i is used elsewhere } 

我想知道是否有一种检测/关闭“崩溃”或“冻结”线程的好方法? 我看了一下文档,但它似乎并不适合我如何使用它…

有人可以帮我弄这个吗? 谢谢

threadPool.submit返回Future Object。 因此,使用此未来的对象,您可以处理任务执行。 通过使用isCancelled() and isDone方法,您可以检查任务是否已取消或已完成。 更多的get()是阻塞调用,它会在解释或取消或执行exception时抛出exception。

 List> list = new ArrayList>(); for (int i = 0; i < objectArray.length; i++) { Future task=threadPool.submit(new ThreadHandler(objectArray[i], i)); // The i is used elsewhere list.add(task); } for(Future future : list){ try{ future.get(); }catch(CancellationException cx){ ... }catch(ExecutionException ex){ ... }catch(InterruptedException ix){ ... } } 

您有一个选择是使用ExecutorCompletionService 。 您通过其submit方法执行任务,然后让一个单独的线程等待poll(long timeout, TimeUnit unit)方法的完成。 以exception终止的任务将返回一个Future ,在get()将抛出ExecutionException

使用超时,您还可以检测在任何任务返回之前已经过了太多时间; 然而,这种行为的有用性在很大程度上取决于您的设置。

您所能做的就是中断取消的任务。 您可以使用ScheduledExecutorService计划要取消的任务

如果您的代码不支持中断,则需要对其进行修复。 在任何接近可靠方式的程序中,这很难以编程方式解决。