在执行程序服务中实现线程超时
现在,我有一个相当基本的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){
...
}
}