API 调用应用程序关闭 javafx

API call on application close javafx

我构建了一个简单的 javafx 应用程序来 运行 在 pc 的网络接口上进行一些操作。在应用程序关闭期间,我需要对远程服务器进行 API 调用以执行一些清理任务。 API 调用的次数可以从 0-20 不等。我已经覆盖了 stop 方法并尝试在关闭应用程序之前在那里调用 API 但由于我使用的是相同的线程,这导致应用程序在关闭时冻结。 Windows,默认情况下等待 5 秒,直到确定应用程序没有响应并给出错误。还有其他方法可以解决这个问题吗? Ps:我的应用程序中还有一个小型 http 服务器 运行ning。

... I'm using the same thread ...

这既是问题也是解决方案。

停止时,JVM 等待 所有非守护线程完成。这也为您提供了您正在寻找的机制。您只需要 运行 一个单独的线程来进行必要的处理。

JavaFX 允许您拦截应用程序线程停止(Application::stop() 方法),您可以在其中启动新线程。这种方法的缺点是无法保证调用 Application::stop()(例如,您可以使用 System::exit() 停止应用程序)。

public class Main extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        stage.show();
    }

    @Override
    public void stop() throws Exception {
        super.stop();

        new Thread(() -> {
            // API call ...
        }).start();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

更好的选择是使用Runtime::addShutdownHook()启动相应的线程。

public class Main extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            // API call ...
        }));
    }
}