我有一个简单的Java ExecutorService
,它运行一些任务对象(实现Callable
接口)。
ExecutorService exec = Executors.newSingleThreadExecutor();
List<CallableTask> tasks = new ArrayList<>();
// ... create some tasks
for (CallableTask task : tasks) {
Future future = exec.submit(task);
result = (String) future.get(timeout, TimeUnit.SECONDS);
// TASKS load some classes and invoke their methods (they may create additional threads)
// ... catch interruptions and timeouts
}
exec.shutdownNow();
当所有任务(要么已完成,要么超时)完成后,我尝试关闭执行器,但它无法停止:exec.isTerminated() = FALSE.
我怀疑一些超时的任务没有被正确终止。
是的,我知道执行器的关闭不能保证任何东西:
除了尽力尝试停止正在处理的活动任务外,没有其他保证。例如,典型的实现将通过{@link Thread#interrupt}取消,因此任何未能响应中断的任务可能永远不会终止。
我的问题是,有没有一种方法可以确保这些(任务)线程将终止?
我想到的最好解决方案是在程序末尾调用System.exit()
,但那样很愚蠢。