所以现在我有一个相当基本的执行器服务,我用它来将程序分解为线程,如下所示:
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<T>
目的。因此,使用这个未来的对象,您可以控制任务的执行。
通过使用isCancelled() and isDone
您可以检查任务是否已取消或完成的方法。更get()
正在阻塞调用,在解释或取消或执行异常时抛出异常。
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){
...
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)