multithreading JavaFX 使用线程和 GUI
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16708931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaFX working with threads and GUI
提问by ksarunas
I have a problem while working with JavaFX and Threads. Basically I have two options: working with Tasks
or Platform.runLater
. As I understand Platform.runLater
should be used for simple/short tasks, and Task
for the longer ones. However, I cannot use any of them.
我在使用 JavaFX 和线程时遇到问题。基本上我有两个选择:使用Tasks
或Platform.runLater
。据我所知,Platform.runLater
应该用于简单/短期任务,以及Task
较长的任务。但是,我不能使用它们中的任何一个。
When I call Thread
, it has to pop up a captcha dialog in a middle of task. While using Task
, it ignores my request to show new dialog... It does not let me to create a new stage.
当我调用 时Thread
,它必须在任务中间弹出一个验证码对话框。使用时Task
,它忽略了我显示新对话框的请求......它不允许我创建一个新阶段。
On the other hand, when I use Platform.runLater
, it lets me show a dialog, however, the program's main window freezes until the pop up dialog is showed.
另一方面,当我使用 时Platform.runLater
,它让我显示一个对话框,但是,程序的主窗口会冻结,直到显示弹出对话框。
I need any kind of solution for this. If anyone knows how to deal with this or had some similar experience and found a solution I am looking forward to hearing from you!
我需要任何解决方案。如果有人知道如何处理这个问题或有一些类似的经验并找到了解决方案,我期待着收到您的来信!
回答by Antonio J.
As puce says, you have to use Task
or Service
for the things that you need to do in background. And Platform.runLater
to do things in the JavaFX Application thread from the background thread.
正如 puce 所说,你必须使用Task
或Service
为你需要在后台做的事情。并Platform.runLater
从后台线程在 JavaFX 应用程序线程中执行操作。
You have to synchronize them, and one of the ways to do that is using the class CountDownLatch
.
您必须同步它们,其中一种方法是使用 class CountDownLatch
。
Here is an example:
下面是一个例子:
Service<Void> service = new Service<Void>() {
@Override
protected Task<Void> createTask() {
return new Task<Void>() {
@Override
protected Void call() throws Exception {
//Background work
final CountDownLatch latch = new CountDownLatch(1);
Platform.runLater(new Runnable() {
@Override
public void run() {
try{
//FX Stuff done here
}finally{
latch.countDown();
}
}
});
latch.await();
//Keep with the background work
return null;
}
};
}
};
service.start();
回答by Puce
Use a Worker
(Task
, Service
) from the JavaFX Application thread if you want to do something in the background.
如果您想在后台执行某些操作,请使用JavaFX 应用程序线程中的Worker
( Task
, Service
)。
http://docs.oracle.com/javafx/2/api/javafx/concurrent/package-summary.html
http://docs.oracle.com/javafx/2/api/javafx/concurrent/package-summary.html
Use Platform.runLater
from a background thread if you want to do something on the JavaFX Application thread.
Platform.runLater
如果您想在 JavaFX 应用程序线程上执行某些操作,请从后台线程使用。