所以我刚才问了一个问题:在这里问了一个问题“如果我的线程花费太长时间,我怎样才能让它们被杀死”
我已经实现了那里提到的解决方案,但是在线程超时的某些罕见情况下,程序仍然可能失败/锁定(请参阅:保持 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 秒时中断。