Lambda从入门到精通之三十八 CompletableFuture异步编程 runAfterXXX方法使用详解

CompletableFuture提供了多个方法,可以支持两个任务的组合执行,提供的方式是runAfter开头的多个方法。
runAfterXXX方法支持等待一个或者两个任务执行完成,然后再执行一个自定义的action,执行自定义action并不使用之前任务的结果,并且执行完也没有返回结果。
我们看一下具体方法:

CompletableFuture<Void> runAfterBoth(CompletionStage<?> other, Runnable action) 
CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other, Runnable action) 
CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other, Runnable action, Executor executor) 
CompletableFuture<Void> runAfterEither(CompletionStage<?> other, Runnable action) 
CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other, Runnable action) 
CompletableFuture<Void> runAfterEitherAsync(CompletionStage<?> other, Runnable action, Executor executor) 
static CompletableFuture<Void> runAsync(Runnable runnable) 
static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor) 

我们再来看一下demo:

import java.util.concurrent.CompletableFuture;

/**
 * 使用CompletableFuture异步编程 runAfterXXX
 * @author www.itzhimei.com
 */
public class FutureTest_12 {

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

        CompletableFuture.supplyAsync(()->FutureTest_12.getTaskResult(1000, "Test Task 1"))
                .runAfterBoth(CompletableFuture.supplyAsync(()->FutureTest_12.getTaskResult(500, "Test Task 2")), ()->System.out.println("runAfterBoth:两个任务都执行完成了")).join();

        System.out.println("==================================================");


        long start = System.currentTimeMillis();
        CompletableFuture.supplyAsync(()->FutureTest_12.getTaskResult(10000, "Test Task 1"))
                .runAfterEither(CompletableFuture.supplyAsync(()->FutureTest_12.getTaskResult(500, "Test Task 2")), ()->System.out.println("runAfterEither:其中一个任务执行完成了")).join();
        long end = System.currentTimeMillis();
        System.out.println("任务执行时间:" + (end-start));

    }

    public static String getTaskResult(long sleepTime, String task) {
        try {
            Thread.sleep(sleepTime);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return task;
    }

}

/* 输出
runAfterBoth:两个任务都执行完成了
==================================================
runAfterEither:其中一个任务执行完成了
任务执行时间:502
 */