JavaFX任务线程没有终止 [英] JavaFX Task threads not terminating

查看:734
本文介绍了JavaFX任务线程没有终止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个JavaFX应用程序,我的对象扩展了Task以提供远离JavaFX GUI线程的并发性。

I am writing a JavaFX application and my objects extend Task to provide concurrency away from the JavaFX GUI thread.

我的Main类看起来像这样:

My Main class looks like this:

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控制器示例看起来像这样(略有抽象) :

My GUI Controller Sample looks like this (abstracted slightly):

ExecutorService threadPool = Executors.newFixedThreadPool(2);
private void handleStartButtonAction(ActionEvent event) {
        MyTask task = new MyTask();
        threadPool.execute(task);
}

目前我的任务只是睡眠并打印数字1到10:

At the moment my task just does a sleep and prints numbers 1 through 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(),它似乎解决了这个问题,虽然我知道这不是正确的方法。

The problem I have is once the task completes it appears as though the thread the task is launched with continues to run. So when I exit the JavaFX application by pressing the "X" top right corner, the JVM continues to run and my application does not terminate. If you look at my main class, I have put in System.exit() which seems to solve the problem though I am aware this is not the correct way.

可以有人建议我在终止我的子线程方面需要做什么,以及这样做的可接受方式是什么?即检查它们是否完整然后终止,例如。

Can someone suggest what I need to do in terms of terminating my child threads, and what is the accepted way of doing this? i.e, checking they are complete and then terminated for example.

谢谢

推荐答案

Javadocs for Executors.newFixedThreadPool()声明:


线程在池中将一直存在,直到明确关闭。

The threads in the pool will exist until it is explicitly shutdown.

同时检查使用示例 ExecutorService ,他们注意始终关闭池。

Also check the the usage examples of ExecutorService, they take care to always shutdown the pool.

您可能必须确保调用 threadPool.shutdown()申请的适当地点。

You probably have to ensure that threadPool.shutdown() is called at the appropriate place of your application.

这篇关于JavaFX任务线程没有终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆