我使用的后台线程不应在 JavaFX 停止时立即停止(就像使用 setImplicitExit
配置的任何阶段都不再打开时一样),所以我不使用 setDaemon
对于这个。但是如何检查 JavaFX 是否正在关闭? (这个线程应该只是完成一些事情然后自己停止)
我知道我可以将 setOnCloseRequest
放入所有阶段,但我不想那样做。
Runtime.getRuntime().addShutdownHook()
在这种情况下不起作用,因为只要该线程正在运行,机器就不会停机。
最佳答案
重写 Application.stop()
并设置一个标志。您的线程将需要定期检查该标志。
中南合作:
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);
}
}
关于java - 检查 JavaFX 平台是否退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31984065/