JavaFX中的多线程挂起了UI

Cli*_*ote 22 java multithreading javafx javafx-2

我有一个简单的JavaFX 2应用程序,有2个按钮,分别是Start和Stop.单击开始按钮时,我想创建一个后台线程,它将进行一些处理并在其进行时更新UI(例如进度条).如果单击停止按钮,我希望线程终止.

我尝试使用javafx.concurrent.Task我从文档中收集的类可以正常工作.但是每当我单击"开始"时,UI都会冻结/挂起而不是保持正常.

她是主Myprogram extends Application类中用于显示按钮的代码:

public void start(Stage primaryStage)
{               
    final Button btn = new Button();
    btn.setText("Begin");

    //This is the thread, extending javafx.concurrent.Task :
    final MyProcessor handler = new MyProcessor();
    btn.setOnAction(new EventHandler<ActionEvent>()
    {
        public void handle(ActionEvent event)
        {                
           handler.run(); 
        }
    });

    Button stop = new Button();
    stop.setText("Stop");
    stop.setOnAction(new EventHandler<ActionEvent>()
        {
             public void handle(ActionEvent event)
             {
                handler.cancel();
             }
        }

    );
    // Code for adding the UI controls to the stage here.
}
Run Code Online (Sandbox Code Playgroud)

这是MyProcessor类的代码:

import javafx.concurrent.Task;
public class MyProcessor extends Task
{   
    @Override
    protected Integer call()
    {
        int i = 0;
        for (String symbol : feed.getSymbols() )
        {
            if ( isCancelled() )
            {
                Logger.log("Stopping!");
                return i;
            }
            i++;
            Logger.log("Doing # " + i);
            //Processing code here which takes 2-3 seconds per iteration to execute
            Logger.log("# " + i + ", DONE! ");            
        }
        return i;
    }
}
Run Code Online (Sandbox Code Playgroud)

非常简单,但只要我点击"开始"按钮,UI就会挂起,尽管控制台消息会继续显示(Logger.log简单地说System.out.println)

我究竟做错了什么?

ass*_*ias 26

Task实现Runnable,所以当你调用handler.run();实际上call在UI线程中运行方法.这会挂起UI.

您应该在后台线程中通过执行程序或只是通过调用来启动任务new Thread(handler).start();.

这在javadocJavaFX并发教程中解释(可能不是很清楚).