【发布时间】:2020-01-24 16:17:35
【问题描述】:
我希望用户等到我的下载文件的方法调用完成,这可能需要大约 2 到 3 分钟。我为方法调用创建了一个新线程,并在run() 方法中调用它。根据返回值,应该显示一条消息,无论是成功还是错误。因此我不得不使用join()。但这仍然冻结,因为 UI 仍在等待方法调用完成。我该如何克服这个问题? (基本上,我需要使用一个线程让UI不冻结,同时我想根据方法的返回值显示一条消息)
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
processMsg.setText("Do not close. This may take few minutes...");
Thread t1 = new Thread(new Runnable(){
@Override
public void run() {
try {
ret = /*Method-call-which-takes-long-time*/
} catch (IOException ex) {
Logger.getLogger(JavaFXApplication1.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(JavaFXApplication1.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
t1.start();
try {
t1.join();
} catch (InterruptedException ex) {
Logger.getLogger(JavaFXApplication1.class.getName()).log(Level.SEVERE, null, ex);
}
if (ret != null){
if (ret.equals("TRUE")){
pane.getChildren().remove(processMsg);
processMsg.setText("File downloaded at location: "+ chosenDir.getAbsolutePath());
pane.add(processMsg,0,11,2,1);
}
else{
pane.getChildren().remove(processMsg);
processMsg.setText(ret);
pane.add(processMsg,0,11,2,1);
}
}
}
});
【问题讨论】:
-
minimal reproducible example 请...不要忘记阅读 fx 中的并发性(以及它是如何支持的)
标签: java multithreading javafx