package com.hzh.corejava.concurrent.completablefuture;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CompletableFuture;

public class CompletableFutureExample {
    private static final Logger logger = LoggerFactory.getLogger(CompletableFutureExample.class);

    public static void main(String[] args) {

        CompletableFuture<Void> cf = CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            logger.info("Download an image from a remove website");
        }).thenRunAsync(() -> {
            logger.info("Render image");
        });

        logger.info("Do something else.");
        cf.join();
        logger.info("end");
    }
}

@@ -153,16 +153,103 @@
 eFuture;
+%0Aimport java.util.concurrent.CompletionException;%0Aimport java.util.concurrent.TimeUnit;
 %0A%0Apublic
@@ -427,16 +427,161 @@
 rgs) %7B%0A%0A
+//        runAsync();%0A//%0A//        completedFutureExample();%0A        completeExceptionallyExample();%0A    %7D%0A%0A    private static void runAsync() %7B%0A
         
@@ -1008,24 +1008,24 @@
  cf.join();%0A
-
         logg
@@ -1045,11 +1045,1250 @@
 );%0A    %7D
+%0A%0A    static void completedFutureExample() %7B%0A        CompletableFuture cf = CompletableFuture.completedFuture(%22message%22);%0A        logger.info(%22Is done:%22 + cf.isDone());%0A        logger.info(%22value now:%22 + cf.getNow(null));%0A    %7D%0A%0A    static void completeExceptionallyExample() %7B%0A        CompletableFuture cf = CompletableFuture.completedFuture(%22message%22).thenApplyAsync(text -%3E %7B%0A//            try %7B%0A//                Thread.sleep(1000);%0A//            %7D catch (InterruptedException e) %7B%0A//                e.printStackTrace();%0A//            %7D%0A//            return text.toUpperCase();%0A            throw new NullPointerException(%22Test%22);%0A        %7D);%0A        CompletableFuture exceptionHandler = cf.handle((s, exception) -%3E %7B%0A            System.out.println(s);%0A            logger.error(exception.toString());%0A            return %22Have handled exception%22;%0A        %7D);%0A//        cf.completeExceptionally(new RuntimeException(%22completed exceptionally%22));%0A        System.out.println(cf.isCompletedExceptionally());%0A        try %7B%0A            cf.join();%0A        %7D catch (CompletionException ex) %7B // just for testing%0A            ex.printStackTrace();%0A        %7D%0A        Object result = exceptionHandler.join();%0A        System.out.println(result);%0A    %7D
 %0A%7D%0A

添加CompletableFuture 例子