【发布时间】:2019-09-25 12:02:47
【问题描述】:
我在通过 completableFuture 设置窗口名称时遇到问题。 我需要获取用户所在的帐户,并以此命名主窗口。
MainWindow mainWindow = this;
...
CompletableFuture.supplyAsync(() -> {
while(true) {
try {
// wait until the account is chosen
if (MainWindow.idAccount > 0 ) {
ResultSet rs = // some request to the db
rs.next();
return rs.getString(1);
}
} catch (Exception e) {
System.out.println("Error while getting the address of the account. " + e.getMessage());
}
}
}).thenAccept(account -> {
System.out.println(account);
mainWindow.setText("POS - " + account);
});
一切正常,实际上在 .thenAccept() 中,控制台打印出正确的帐户地址。但是,文本永远不会设置。
可能是关于线程之间的访问吗?提前致谢。
【问题讨论】:
-
您的
supplyAsync阶段正在公共 fork-join 池中执行,但更新 UI 必须发生在 UI 线程上(例如 Event Dispatch Thread (EDT ) 在 Swing 中)。您应该使用thenAcceptAsync变体在 UI 线程上安排舞台——请参阅my other comment。