java - 在原线程中运行 CompletableFuture 的 whenComplete
问题描述
如何在创建 CompletableFuture 的原始线程中whenComplete
运行?CompletableFuture
// main thread
CompletableFuture
.supplyAsync(() -> {
// some logic here
return null;
}, testExecutorService);
.whenComplete(new BiConsumer<Void, Throwable>() {
@Override
public void accept(Void aVoid, Throwable throwable) {
// run this in the "main" thread
}
});
解决方案
JavaFx 的扩展示例:
button.setOnClick((evt) -> {
// the handler of the click event is called by the GUI-Thread
button.setEnabled(false);
CompletableFuture.supplyAsync(() -> {
// some logic here (runs outside of GUI-Thread)
return something;
}, testExecutorService);
.whenComplete((Object result, Throwable ex) -> {
// this part also runs outside the GUI-Thread
if (exception != null) {
// something went wrong, handle the exception
Platform.runLater(() -> {
// ensure we update the GUI only on the GUI-Thread
label.setText(ex.getMessage());
});
} else {
// job finished successfull, lets use the result
Platform.runLater(() -> {
label.setText("Done");
});
}
Platform.runLater(() -> {
button.setEnabled(true); // lets try again if needed
});
});
});
这不是您在这种情况下可以编写的最好的代码,但它应该能够说明这一点。
推荐阅读
- docker - 码头工人--net与--network
- c++ - 模板化 extern "C" 函数以从 C++ 调用不同类型的 Fortran 函数
- svg - SVG xlink:href 在 Chrome 中不起作用
- php - NelmioApiDocBundle 不生成文档
- excel - 使用或在excel中的平均ifs
- c# - Microsoft Bot 框架程序集参考
- c# - 如何使用 C# 和 XNA 进行双跳?
- c# - Breeze.net:在端点返回之前应用 ODATA 过滤器
- ms-access - 尝试查询多选列表框时出现错误 3131
- c++ - Microsoft C++ 异常:内存位置的 boost::archive::archive_exception(通过客户端服务器 Boost Udp 解析向量)