首页 > 解决方案 > 在原线程中运行 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 
                }
            });

标签: java

解决方案


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
            });
        });
    });

这不是您在这种情况下可以编写的最好的代码,但它应该能够说明这一点。


推荐阅读