我在我的UI线程中调用一个方法。在此方法中,将创建一个新线程。我需要UI线程一直等到这个新线程完成,因为我需要这个线程的结果来继续UI线程中的方法。但是我不想在等待的时候冻结UI。有没有办法让UI线程在不忙于等待的情况下等待?
发布于 2015-04-22 22:30:55
您不应该让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块中的代码:
任务完成后,必须执行
因此,这个解决方案可以通过“等待任务完成”来做任何事情,但不会同时阻塞UI线程。
发布于 2015-04-22 22:23:40
只需调用一个在线程完成时通知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();
}
}
}https://stackoverflow.com/questions/29800410
复制相似问题