使JavaFX应用程序线程等待另一个Thread完成 [英] Make JavaFX application thread wait for another Thread to finish

查看:142
本文介绍了使JavaFX应用程序线程等待另一个Thread完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在UI线程中调用一个方法。在此方法中,将创建一个新线程。我需要UI线程等到这个新线程完成,因为我需要这个线程的结果来继续UI线程中的方法。但我不想在等待时冻结UI。有没有办法让UI线程在没有忙等待的情况下等待?。

I am calling a method inside my UI thread. Inside this method a new thread is created. I need the UI thread to wait until this new thread is finished because I need the results of this thread to continue the method in the UI thread. But I don´t want to have UI frozen while its waiting. Is there some way to make the UI thread wait without busy waiting?.

推荐答案

你永远不应该让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.

这篇关于使JavaFX应用程序线程等待另一个Thread完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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