JavaFX中的Platform.runLater和Task [英] Platform.runLater and Task in JavaFX

查看:184
本文介绍了JavaFX中的Platform.runLater和Task的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究这个问题,但至少我还是非常困惑。

I have been doing some research on this but I am still VERY confused to say the least.

任何人都可以给我一个具体的例子来说明何时使用任务以及何时使用 Platform.runLater(Runnable); ?究竟有什么区别?什么时候使用其中任何一个是否有黄金法则?

Can anyone give me a concrete example of when to use Task and when to use Platform.runLater(Runnable);? What exactly is the difference? Is there a golden rule to when to use any of these?

如果我错了也不是这两个对象是另一种创造另一种方式的方法GUI中主线程内的线程(用于更新GUI)?

Also correct me if I'm wrong but aren't these two "Objects" a way of creating another thread inside the main thread in a GUI (used for updating the GUI)?

推荐答案

使用平台。 runLater(...)用于快速和简单的操作,任务用于复杂和大型操作。

Use Platform.runLater(...) for quick and simple operations and Task for complex and big operations .

  • Use case for Platform.runLater(...)
  • Use case for Task: Task Example in Ensemble App

示例:为什么我们不能使用 Platform.runLater(... )用于长计算(取自下面的参考文献)。

Example: Why Can't we use Platform.runLater(...) for long calculations (Taken from below reference).

问题:背景知识hread,其数量从0到100万,并在UI中更新进度条。

Problem: Background thread which just counts from 0 to 1 million and update progress bar in UI.

代码使用 Platform.runLater(。 ..)

final ProgressBar bar = new ProgressBar();
new Thread(new Runnable() {
    @Override public void run() {
    for (int i = 1; i <= 1000000; i++) {
        final int counter = i;
        Platform.runLater(new Runnable() {
            @Override public void run() {
                bar.setProgress(counter / 1000000.0);
            }
        });
    }
}).start();




这是一个可怕的代码,是对自然的犯罪(和
编程一般)。首先,在Runnables的双重嵌套中,你只会看到
的脑细胞。其次,它将使用少量Runnables淹没
事件队列 - 实际上是其中的一百万个。
显然,我们需要一些API,以便更容易编写后台
工作人员,然后与UI进行通信。

This is a hideous hunk of code, a crime against nature (and programming in general). First, you’ll lose brain cells just looking at this double nesting of Runnables. Second, it is going to swamp the event queue with little Runnables — a million of them in fact. Clearly, we needed some API to make it easier to write background workers which then communicate back with the UI.

代码使用任务:

Code using Task :

Task task = new Task<Void>() {
    @Override public Void call() {
        static final int max = 1000000;
        for (int i = 1; i <= max; i++) {
            updateProgress(i, max);
        }
        return null;
    }
};

ProgressBar bar = new ProgressBar();
bar.progressProperty().bind(task.progressProperty());
new Thread(task).start();




它没有上一个代码中出现的任何缺陷

it suffers from none of the flaws exhibited in the previous code

参考:
JavaFX 2.0中的工作线程

这篇关于JavaFX中的Platform.runLater和Task的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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