在执行程序服务中实现线程超时 [英] Implementing thread timeout in executor service

查看:78
本文介绍了在执行程序服务中实现线程超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So right now I have a fairly basic Executor service that I use to break my program into threads, like so:

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
}

我想知道是否存在检测/关闭崩溃"或冻结"线程的好方法?我看了看文档,但它似乎与我的使用方式完全不匹配...

I was wondering if there was a good way to detect / close "crashed" or "frozen" threads? I took a look at the documentation but it doesn't really seem to fit in with how I'm using this at all...

有人可以帮我吗?谢谢

推荐答案

threadPool.submit返回Future<T>对象.因此,使用此将来的对象,您可以处理任务执行. 通过使用isCancelled() and isDone方法,您可以检查任务是否已取消或完成.甚至更多的get()阻止了在解释,取消或执行异常时引发异常的调用.

threadPool.submit returns Future<T> Object. So using this future Object you can have handle on your task execution. By using isCancelled() and isDone method you can check task has been canceled or done. Even more get() is blocking call which throws exception on interpret or cancel or in executionexception.

List<Future<?>> list = new ArrayList<Future<?>>();
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){
   ...
   }

}

这篇关于在执行程序服务中实现线程超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆