当我使用ScheduledExecutorService
(或ExecutorService)并提交Runnable时,我的关闭挂钩永远不会被调用。例如,该程序挂起:
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);
}
}
由于执行者的线程不是守护进程,因此我希望可以调用shutdown钩子,但事实并非如此。知道为什么吗?
最佳答案
如果您绝对需要在任务运行后关闭执行程序,则可以执行以下操作:
static {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
Logger.getGlobal().info("destroying");
exec.shutdownNow();
}
});
}
public static void main(String[] args) throws Exception {
Future f = exec.schedule(new Runnable() {
@Override
public void run() {
Logger.getGlobal().info("thread run");
}
}, 10, TimeUnit.SECONDS);
while (!f.isDone()) {
Logger.getGlobal().info("waiting for task to finish");
Thread.sleep(1000);
}
Runtime.getRuntime().exit(0);
}
关于java - ScheduledExecutorService和Shutdown Hook,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32982045/