![](/img/trans.png)
[英]How to prevent CompletableFuture#whenComplete execution in context thread
[英]Run whenComplete of CompletableFuture in original thread
我怎样才能运行whenComplete
的的CompletableFuture
在原来的线程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
});
});
});
在这种情况下,这不是您可以编写的最佳代码,但是应该可以理解这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.