所以我刚才问了一个问题: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 秒时停止运行。
最佳答案
因为我怀疑你的工作线程仍在运行。您正在调用 future.cancel(true); ,但所做的只是在线程上设置中断标志 - 它不会主动中断您正在运行的代码。 “中断”代码的另一种方法是将一些 volatile boolean 关闭
标志设置为true,并在代码中测试它。请参阅此处 more details about interrupting threads .
您需要确保您的ThreadHandler
代码正确处理中断。例如,它需要检查循环或其他代码块中的 Thread.currentThread().isInterrupted()。您还需要确保正确处理 InterruptedException,而不仅仅是吞掉中断。
参见my answer here有关线程中断的更多信息。
关于java - 为什么我的线程失败时不会超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12916580/