我正在UI线程中调用一个方法。在这个方法内部创建了一个新线程。我需要UI线程等待直到新线程完成,因为我需要该线程的结果来继续UI线程中的方法。但我不想在等待时使UI冻结。有没有一些方法可以让UI线程等待而不是忙等待?
永远不要让FX应用程序线程等待;这会冻结UI并使其无响应,无法处理用户操作和呈现任何内容到屏幕。
如果你想在长时间运行的进程完成后更新UI,请使用javafx.concurrent.Task
API。例如:
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
为表示长时间运行过程结果的任何数据类型。
请注意onSucceeded
块中的代码:
task.getValue()
访问后台任务执行的结果因此,这种解决方案可以做到等待任务完成时能做的任何事情,但同时不会阻塞UI线程。
只需调用一个方法,当线程完成时通知GUI。类似于这样:
class GUI{
public void buttonPressed(){
new MyThread().start();
}
public void notifyGui(){
//thread has finished!
//update the GUI on the Application Thread
Platform.runLater(updateGuiRunnable)
}
class MyThread extends Thread{
public void run(){
//long-running task
notifyGui();
}
}
}