簡體   English   中英

在原始線程中的CompletableFuture完成時運行

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM