简体   繁体   English

JAVA 中的 CompletableFuture 完成序列

[英]CompletableFuture completion sequence in JAVA

I wrote a simple program我写了一个简单的程序

import java.util.concurrent.*;
public class TestCompletableFuture {
    
    public static void main(String[] args) throws Exception {
        CompletableFuture<Void> future = new CompletableFuture<Void>()
            .whenComplete((res, exc) -> {
                System.out.println("inside handle.");
                if (exc != null) {
                    System.out.println("exception.");
                }
                System.out.println("completed.");
            }
        );

        future.completeExceptionally(new Exception("exception"));
        System.out.println("finished.");
    }
}

the output of the code:代码的output:

finished.

When the main thread calls future, my understanding is.当主线程调用future时,我的理解是。 The method supplied into CompletableFuture should be called by completeExceptionally().提供给 CompletableFuture 的方法应该由 completeExceptionally() 调用。 whenComplete().当完成()。

Why isn't that the case?为什么不是这样呢?

This is a result of you finishing the incorrect future.这是你完成错误未来的结果。 To see the whenComplete in action, you must obtain a reference to the first step and finish it:要查看whenComplete的运行情况,您必须获得对第一步的引用并完成它:

public class TestCompletableFuture {

    public static void main(String[] args) throws Exception {

        /** get reference */
        CompletableFuture<Void> future = new CompletableFuture<>();
        
        /** configure the action that to be run when the future is complete */
        CompletableFuture<Void> future2 = future
                .whenComplete((res, exc) -> {
                            System.out.println("inside handle.");
                            if (exc != null) {
                                System.out.println("exception.");
                            }
                            System.out.println("completed.");
                        }
                );

        future.completeExceptionally(new Exception("exception"));
        System.out.println("finished.");
    }
}

The code is now self-explanatory... Run the (res, exc) -> action when the future is finished.代码现在是不言自明的...运行(res, exc) -> future完成时的操作。 And simply use completeExceptionally(...) on the future to bring about that completion.并简单地在future使用completeExceptionally(...)来完成。

Also to be noted is the exceptional completion of all the aforementioned stages (futures) at this time:还需要注意的是此时所有上述阶段(期货)的异常完成:

System.out.println(future.isDone()); // true
System.out.println(future2.isDone()); // true

System.out.println(future.isCompletedExceptionally()); // true
System.out.println(future2.isCompletedExceptionally()); // true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM