且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使JavaFX应用程序线程等待另一个Thread完成

更新时间:2022-05-28 21:50:45

你永远不应该让FX应用程序线程等待;它会冻结UI并使其无响应,无论是在处理用户操作方面还是在向屏幕呈现任何内容方面。

You should never make the FX Application Thread wait; it will freeze the UI and make it unresponsive, both in terms of processing user action and in terms of rendering anything to the screen.

如果您要更新UI当长时间运行的过程完成后,使用 javafx.concurrent.Task API 。例如

If you are looking to update the UI when the long running process has completed, use the javafx.concurrent.Task API. E.g.

someButton.setOnAction( event -> {

    Task<SomeKindOfResult> task = new Task<SomeKindOfResult>() {
        @Override
        public SomeKindOfResult call() {
            // process long-running computation, data retrieval, etc...

            SomeKindOfResult result = ... ; // result of computation
            return result ;
        }
    };

    task.setOnSucceeded(e -> {
        SomeKindOfResult result = task.getValue();
        // update UI with result
    });

    new Thread(task).start();
});

显然用任何数据类型代替 SomeKindOfResult 长期运行过程的结果。

Obviously replace SomeKindOfResult with whatever data type represents the result of your long-running process.

请注意 onSucceeded 块中的代码:


  1. 必须在任务完成后执行

  2. 可以访问后台任务的执行结果,通过 task.getValue()

  3. 基本上与您启动任务的地方在同一范围内,因此它可以访问所有UI元素等。

因此,这个解决方案可以通过等待任务完成做任何事情,但是在此期间不会阻止UI线程。

Hence this solution can do anything you could do by "waiting for the task to finish", but doesn't block the UI thread in the meantime.