有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在原始线程中完成CompletableFuture时运行

如何在创建CompletableFuture的原始线程中运行whenComplete

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

共 (1) 个答案

  1. # 1 楼答案

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

    在这种情况下,这不是你能写的最好的代码,但它应该能让你明白这一点