【发布时间】:2018-04-21 09:09:22
【问题描述】:
我有一个简单的应用程序,它在后台更新数据,当它更新时,它会禁用所有其他按钮并启用 TextArea 来显示进度。
步骤:
-
禁用 mainUI 中的所有其他按钮(按钮名称:plotButton)
-
启用显示更新已开始的 TextArea(TextArea 名称:infoLogTextArea)
-
然后只启动更新方法(update() 抛出异常)。
代码如下:
@FXML
public void handleUpdateButton() {
infoLogTextArea.setVisible(true);
infoLogTextArea.appendText("Please wait while downloading data from internet.....\n");
plotButton.setDisable(true);
updateButton.setDisable(true);
if(c!=null) {
Runnable task = new Runnable() {
@Override
public void run() {
// Thread.sleep(10000); -> sleep for 10secs
Platform.runLater(new Runnable() {
@Override
public void run() {
try {
c.updateData();
infoLogTextArea.appendText(c.getErrorLog().toString());
plotLabel.setText(c.getCityData().size()+" cities found and updated from internet");
infoLogTextArea.appendText("Successfully updated the data from Internet\n");
}catch (IOException e) {
infoLogTextArea.setText("Couldnot update the data from web: "+e.getMessage()+"\n");
}
finally {
plotButton.setDisable(false);
updateButton.setDisable(false);
}
}
});
}
};
new Thread(task).start();
}else {
System.out.println("c not initialized");
}
}
现在代码运行良好,但有时第 1 步和第 2 步未执行,它开始第 3 步(更新),这可能会冻结程序。 如果我将 Thread.sleep(10 secs) 放在第 2 步和第 3 步之间,那么它完全没问题。 (代码中有注释)
但是任何人都可以解释幕后发生的事情以及为什么Platform.runLater() 不能一直工作吗?
【问题讨论】:
-
不是真正的直接重复,但看看这个答案:stackoverflow.com/questions/34985943/… 假设
c.updateData()需要很长时间,你应该把它放在runLater调用之外。换句话说 - 仅在Platform.runLater中包装实际更改 UI 的调用。
标签: java multithreading javafx runnable