CompletableFuture的使用


CompletableFuture

常用方法

supplyAsync

异步执行任务,任务有返回值

public class SupplyAsyncDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName());
            return "hello";
        }, executorService);
        System.out.println(future.get());
        executorService.shutdown();
    }
}

runAsync

异步执行任务,任务没有返回值

可以看到返回的类型是Void,并且future.get()获得的结果值为null

public class RunAsyncDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            System.out.println(Thread.currentThread().getName());
        }, executorService);
        System.out.println(future.get());
        executorService.shutdown();
    }
}

then

前一个异步任务执行完,然后执行本任务

当前执行thenApply()方法的线程来负责执行本任务,比如main线程,但是如果前一个异步任务还没执行完,那么main线程就不能执行本任务了,得等前一个任务执行完后才能执行本任务,这个时候就会让执行前一个任务的线程上执行本任务,这样才能保证执行顺序

如:有taskA与taskB, 如果main线程执行到future1.thenApply(taskB)时,taskA已经执行完成了,那么taskB任务将由main线程执行,如果taskA还没执行完,那么taskB将由其他线程执行。

public class ThenDemo {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        Supplier<String> taskA = () -> {
            System.out.println("1:" + Thread.currentThread().getName());
            return "Hello";
        };
        Function<String, String> taskB = s -> {
            System.out.println("2:" + Thread.currentThread().getName());
            return s + " World";
        };
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(taskA);
        //Thread.sleep(5000);
        CompletableFuture<String> future2 = future1.thenApply(taskB);
        System.out.println(future2.get());
    }
}

thenAsync

会利用Completable Future中公共的Fork Join Pool来执行任务

thenApply

任务类型 Function<? super T, ? extends U> fn

有入参,有返回值

thenAccept

任务类型 Consumer<? super T> action

有入参,无返回值

thenRun

任务类型 Runnable action

无入参,无返回值

thenCompose

任务类型 Function<> super T, ? extends CompletionStage> fn

有入参,有返回值,返回值类型只能是Completion Stage

按顺序执行两个并行任务

thenCombine

任务类型 CompletionStage<? extends U other, BiFunction<? super T, ? superU, ? extends V>> fn

有两个入参

  • 第一个参数为CompetionStage
  • 第二个参数为具体要执行的任务,任务类型为Bi Function, 有两个入参,一个返回值

整合两个并行执行的任务结果

runAfterEither

两个任务中任意一个完成了,就执行回调

runAfterBoth

两个任务都完成了,才执行回调

get()

阻塞等待结果

V get(long timeout, TimeUnit unit)

超时等待结果

T getNow(T valueIfAbsent)

立即获取结果,如果任务还没完成,则返回valueIfAbsent

whenComplete

入参为 biConsumer<? super T, ? super Throwable> action

  • 任务正常结束第一个参数传入的是结果
  • 任务异常结束第二个参数的是一场

没有返回值


文章作者: Tariq
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Tariq !
  目录