【发布时间】:2012-10-06 15:56:06
【问题描述】:
所以我不久前问了一个问题:Over here 问了一个问题“如果我的线程花费太长时间,我怎样才能让它们被杀死”
我已经实现了那里提到的解决方案,但在某些罕见的线程超时的情况下,程序仍然可能失败/锁定(请参阅:保持 main() 方法打开,并防止程序的进一步 cron 运行)。
这是我正在使用的来源:
//Iterate through the array to submit them into individual running threads.
ExecutorService threadPool = Executors.newFixedThreadPool(12);
List<Future<?>> taskList = new ArrayList<Future<?>>();
for (int i = 0; i < objectArray.length; i++) {
Future<?> task = threadPool.submit(new ThreadHandler(objectArray[i], i));
taskList.add(task);
Thread.sleep(500);
}
//Event handler to kill any threads that are running for more than 30 seconds (most threads should only need .25 - 1 second to complete.
for(Future future : taskList){
try{
future.get(30, TimeUnit.SECONDS);
}catch(CancellationException cx){ System.err.println("Cancellation Exception: "); cx.printStackTrace();
}catch(ExecutionException ex){ System.err.println("Execution Exception: ");ex.printStackTrace();
}catch(InterruptedException ix){ System.err.println("Interrupted Exception: ");ix.printStackTrace();
}catch(TimeoutException ex) {future.cancel(true);}
}
threadPool.shutdown();
threadPool.awaitTermination(60, TimeUnit.SECONDS);
所以我的问题是:实现了这段代码后,为什么执行器服务没有在 30 秒时中断。
【问题讨论】:
-
注意:每个任务的超时时间都会增加。例如如果第一个任务需要 29 秒,那么您的第二个任务需要 59 秒才能完成。
-
你能评论一下如何解决这个问题吗?因为那不是故意的。
-
我已经为导致超时时间较长的原因之一添加了答案/解决方案。
标签: java multithreading timeout executorservice