我正在尝试构建类似后台任务执行器的东西,如果没有答案,它会在一定时间后终止后台任务(后台任务调用 web 服务,它们可能会超时,但我需要确保它们在一定时间内超时时间)
所以我将此作为实验,但如果我运行此程序,程序不会终止。我想知道是不是因为后台线程仍然处于 Activity 状态?我怎样才能关闭它?
public class Test {
public static class Task implements Callable<Object> {
@Override
public Object call() throws Exception {
while(true) {}
}
}
public static void main(String[] args) {
try {
Task t = new Task();
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.invokeAll(Arrays.asList(t), 5L, TimeUnit.SECONDS);
executor.shutdown();
System.out.println("DONE");
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
最佳答案
ExecutorService 不会杀死正在运行的线程,并且由于线程是作为非守护进程创建的,因此 JVM 不会退出。
当超时到期时,invokeAll() 返回的 futures 被取消,这意味着在 future 对象上设置了一个标志,你会得到一个 CancellationException
如果您尝试调用 future.get()
。然而,invokeAll() 和 shutdown()(或 shutdownNow())都没有做任何事情来终止线程。
请注意,您甚至不能自己终止线程。您所能做的就是设置一些特定于应用程序的标志或调用 Thread.interrupt()
,但即使那样也不能保证 the thread terminates .
关于Java ExecutorService - 为什么这个程序一直在运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32301891/