2023-02-16 396
我正在编写一个Javafx应用程序,而我的对象扩展了任务,以便从Javafx GUI线程提供并发.
我的主要班级看起来像这样:
public class MainApp extends Application {
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("Sample.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
public void handle(WindowEvent t) {
//I have put this in to solve the threading problem for now.
Platform.exit();
System.exit(0);
}
});
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
我的GUI控制器样本看起来像这样(稍微抽象):
ExecutorService threadPool = Executors.newFixedThreadPool(2);
private void handleStartButtonAction(ActionEvent event) {
MyTask task = new MyTask();
threadPool.execute(task);
}
目前我的任务只是睡觉,并打印数字1至10:
public class MyTask extends Task<String> {
@Override
protected String call() throws Exception {
updateProgress(0.1, 10);
for (int i=0;i<=10;i++) {
if (isCancelled()) {
break;
}
Thread.sleep(1000);
System.out.println(i);
updateProgress(i, 10);
}
return "Complete";
}
}
我遇到的问题是,一旦任务完成,就好像在继续运行任务的线程一样.因此,当我按下” X”右上角退出JAVAFX应用程序时,JVM继续运行,并且我的应用程序不会终止.如果您看我的主要课程,我已经输入了System.exit(),这似乎可以解决问题,尽管我知道这不是正确的方法.
有人可以建议我在终止孩子线程方面需要做什么,而接受的方法是什么?即,检查它们已完成然后终止.
谢谢
javadocs 对于Executors.newFixedThreadPool()说明:
池中的线程将存在直到明确关闭为止.
还要检查用法示例,他们注意始终关闭池.
您可能必须确保在应用程序的适当位置调用threadPool.shutdown().
Nikos提供的方法(调用关闭)是良好而直接的.
替代方案是定义自己的线程工厂以创建线程.在您的线程工厂中,制作线程守护程序线程.当所有非daemon线程完成时
ExecutorService threadPool = Executors.newFixedThreadPool(
2,
new ThreadFactory() {
AtomicInteger a = new AtomicInteger(1);
public Thread newThread(Runnable r) {
Thread t = new Thread(r, "mythread-" + a.getAndIncrement());
t.setDaemon(true);
return t;
}
}
);
守护程序线程不适合所有服务,有时明确的关闭处理更好.
守护程序线程工厂的方法用于JDK的几个地方.
以上所述是小编给大家介绍的JavaFX任务线程未终止,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对77isp云服务器技术网的支持!
原文链接:https://77isp.com/post/34087.html
=========================================
https://77isp.com/ 为 “云服务器技术网” 唯一官方服务平台,请勿相信其他任何渠道。
数据库技术 2022-03-28
网站技术 2022-11-26
网站技术 2023-01-07
网站技术 2022-11-17
Windows相关 2022-02-23
网站技术 2023-01-14
Windows相关 2022-02-16
Windows相关 2022-02-16
Linux相关 2022-02-27
数据库技术 2022-02-20
抠敌 2023年10月23日
嚼餐 2023年10月23日
男忌 2023年10月22日
瓮仆 2023年10月22日
簿偌 2023年10月22日
扫码二维码
获取最新动态