JavaFX:在单独的线程中运行任务不允许运行任何其他任务 [英] JavaFX: Running a Task in a separate thread doesn't allow anything else to run

查看:659
本文介绍了JavaFX:在单独的线程中运行任务不允许运行任何其他任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在我的程序中不断更新数据,所以我认为通过使用JavaFX的任务,我可以让它在我的程序中作为一个单独的进程运行。

  final任务任务=新任务< Void>(){
@Override
protected Void call()抛出异常{
Platform.runLater (() - > {
while(true){
itemData.forEach(data - > {
System.out.println(data.getId());
});
}
});
返回null;
}
};
Thread thread = new Thread(task);
thread.setDaemon(true);
thread.start();

这是在提供的 initialize 方法中声明的通过可初始化界面。



然而,在运行此程序时,任务是唯一运行的,甚至虽然任务是在一个单独的线程上运行的。为什么会这样做并且没有像预期的那样运行?

解决方案

你刚开始一项任务只是用它来发布一个UI线程上的长时间运行任务。 Runnable

 () - > {
while(true){
itemData.forEach(data - > {
System.out.println(data.getId());
});
}
}

仍在应用程序线程上运行,阻止它。 / p>

只应在应用程序线程上进行UI更新。繁重的工作应该在另一个线程上完成。



您应该只在应用程序线程上发布更新。这样的事情:

  @Override 
protected Void call()抛出异常{
而(true) {
try {
//在更新之间添加暂停
Thread.sleep(1000);
} catch(InterruptedException ex){
}
Platform.runLater(() - > itemData.forEach(data - > {
System.out.println(data。 getId());
}));
}
}

如果您经常发布更新,这也可以使应用程序没有响应。


I need constant data updating in my program, so I thought that through the use of JavaFX's Task that I would be able to have it run as a separate process in my program.

final Task task = new Task<Void>() {
    @Override
    protected Void call() throws Exception {
        Platform.runLater(() -> {
            while (true) {
                itemData.forEach(data -> {
                    System.out.println(data.getId());
                });
            }
        });
        return null;
    }
};
Thread thread = new Thread(task);
thread.setDaemon(true);
thread.start();

This is declared in the initialize method provided by the Initializable interface.

When running this program, however, the task is the only thing that runs, even though the task is run on a separate thread. Why would it do this and not run like intended?

解决方案

You're just starting a task only to use it to post a long running task on the UI thread. The Runnable

() -> {
    while (true) {
        itemData.forEach(data -> {
            System.out.println(data.getId());
        });
    }
}

still runs on the application thread, blocking it.

Only UI updates should be done on the application thread. The heavy work should be done on the other thread.

You should instead post only the updates on the application thread. Something like this:

@Override
protected Void call() throws Exception {
    while (true) {
        try {
            // add a pause between updates
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
        }
        Platform.runLater(() -> itemData.forEach(data -> {
            System.out.println(data.getId());
        }));
    }
}

If you post updates too often, this can also make the application unresponsive.

这篇关于JavaFX:在单独的线程中运行任务不允许运行任何其他任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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