当我使用 ScheduledExecutorService
(或 ExecutorService)并提交一个 Runnable 时,我的关闭钩子(Hook)永远不会被调用。例如,这个程序挂起:
public class App {
static ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
static {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
exec.shutdownNow();
}
});
}
public static void main(String[] args) {
exec.schedule(new Runnable() {
@Override
public void run() {
}
}, 10, TimeUnit.SECONDS);
}
}
由于执行者的线程不是守护进程,我希望调用关闭 Hook ,但事实并非如此。知道为什么吗?
最佳答案
来自 Runtime#addShutdownHook(Thread)
的 javadoc :
The Java virtual machine shuts down in response to two kinds of events:
- The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or
- The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.*
正如您自己所说,newSingleThreadScheduledExecutor
返回的Executor
中的线程不是守护线程。因此它们必须在您的关闭钩子(Hook)被调用之前退出。
你在倒退。您需要从程序执行的其他部分关闭您的 Executor
,而不是关闭 Hook 。关闭 Hook 将在 Executor
终止后运行。
* 假设您没有尝试向您的 java
进程发送用户中断。
关于java - ScheduledExecutorService 和 Shutdown Hook ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32982045/