如何优雅地退出 Java 应用程序



>我有一个Java应用程序,它使用Executors.newSingleThreadScheduledExecutor定期运行一些函数

main()函数中,我永远等待使用:

Thread.currentThread().join();

java应用程序能否识别出它正在关闭(即通过Ctrl-C,Ctrl-D信号),特别是运行计划任务的线程?

这个想法是优雅地关闭应用程序。

Java 运行时注册一个shutdown hook。JVM 的关闭将在注册的线程上收到通知。下面是一个示例:

public class Main {
    public static void main(String[] args) {
        Runtime.getRuntime().addShutdownHook(new ShutDownHookThread());
        while (true) {
        }
    }
}
class ShutDownHookThread extends Thread {
    @Override
    public void run() {
       // ***write your code here to handle any shutdown request
        System.out.println("Shut Down Hook Called");
        super.run();
    }
}

要正常关闭执行程序服务,您需要按以下步骤操作

  1. executorService.shutdownNow();
  2. executorService.awaitTermination();

1 执行程序将尝试中断它管理的线程,并拒绝提交所有新任务。

  1. 稍等片刻,让现有任务终止

下面是正常执行程序关闭的示例

pool.shutdown(); // Disable new tasks from being submitted
try {
    // Wait a while for existing tasks to terminate
    if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
        pool.shutdownNow(); // Cancel currently executing tasks
        // Wait a while for tasks to respond to being cancelled
        if (!pool.awaitTermination(60, TimeUnit.SECONDS))
            System.err.println("Pool did not terminate");
    }
} catch (InterruptedException ie) {
    // (Re-)Cancel if current thread also interrupted
    pool.shutdownNow();
    // Preserve interrupt status
    Thread.currentThread().interrupt();
}

请在这里找到完整的详细声明

希望有所帮助

添加关机挂钩来处理信号。在处理程序中,使其停止生成周期线程,并加入或强制终止现有线程。

相关内容

最新更新