编程语言
首页 > 编程语言> > 检查JavaFX平台是否正在退出

检查JavaFX平台是否正在退出

作者:互联网

我使用了一个后台线程,该线程不应在JavaFX停止时立即停止(就像在再也没有通过setImplicitExit配置打开任何阶段时那样),因此我不为此使用setDaemon.但是,如何检查JavaFX是否已关闭? (该线程应该完成一些事情并停止运行)

我知道我可以将setOnCloseRequest放到所有阶段,但是我宁愿不这样做.

Runtime.getRuntime().addShutdownHook()在这种情况下不起作用,因为只要此线程正在运行,机器就不会停机).

解决方法:

重写Application.stop()并设置一个标志.您的线程将需要定期检查该标志.

SSCCE:

import java.util.concurrent.atomic.AtomicBoolean;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class ExitThreadGracefullyOnExit extends Application {

    AtomicBoolean shutdownRequested = new AtomicBoolean();

    @Override
    public void start(Stage primaryStage) {

        Label countLabel = new Label();

        Thread thread = new Thread(() -> {
            try {
                int count = 0 ;
                while (! shutdownRequested.get()) {
                    count++ ;
                    final String message = "Count = "+count ;
                    Platform.runLater(() -> countLabel.setText(message));
                    Thread.sleep(1000);
                }
                System.out.println("Shutdown... closing resources");
                Thread.sleep(1000);
                System.out.println("Almost done...");
                Thread.sleep(1000);
                System.out.println("Exiting thread");
            } catch (InterruptedException exc) {
                System.err.println("Unexpected Interruption");
            }
        });

        VBox root = new VBox(10, countLabel);
        root.setAlignment(Pos.CENTER);

        thread.start();

        Scene scene = new Scene(root, 350, 100);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    @Override
    public void stop() {
        shutdownRequested.set(true);
    }

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

标签:multithreading,javafx,javafx-8,java
来源: https://codeday.me/bug/20191119/2039553.html