如何优雅地退出 java 应用程序?

How to exit gracefully a java application?

我有一个 java 应用程序,它使用 Executors.newSingleThreadScheduledExecutor

定期运行一些功能

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

Thread.currentThread().join();

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

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

要正常关闭 Executor 服务,您需要按照以下步骤进行

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

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

  1. 等待现有任务终止

下面是正常关闭 Executor 的示例

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();
}

请找到here完整详细的答案

希望得到帮助

添加一个 shutdown hook 来处理信号。在处理程序中,使其停止生成周期线程,并加入或强制终止现有线程。

向 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();
    }
}