2_CompletableFuture

1. CompletableFuture概述

  1. Future接口实现了异步的功能,而CompletableFuture在此基础上进行了功能强化。
  2. CompletableFuture实现了Future和CompletionStage接口
截屏2022-07-14 10.08.16

2. CompletionStage接口

  1. CompletionStage代表异步计算过程中的某一个阶段,一个阶段完成后可能会触发另外一个阶段
  2. 一个阶段的执行可能是被单个阶段的完成触发,也可能是由多个阶段一起触发.有些类似Linux系统的管道分隔符传参数
public class CompletableFutureTest2 {
    public static void main(String[] args)throws Exception {
        /**
         1.当一个线程依赖另一个线程时,可以使用thenApply()方法来把这两个线程串行化(第二个任务依赖第一个任务的结果)
         public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn)
         2.它可以处理正常的计算结果,或者异常情况
         public CompletableFuture<T> whenComplete(BiConsumer<? super T,? super Throwable> action)
         3.异常的处理操作
         public CompletableFuture<T> exceptionally(Function<Throwable,? extends T> fn)
         */
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            try { TimeUnit.SECONDS.sleep(2);  } catch (InterruptedException e) {e.printStackTrace();}
            return 1;
        }).thenApply(result -> {
            return result+3;
        // whenComplete虽然得到异常信息,但是无法修改返回数据
        }).whenComplete((v,e)->{
            if(e==null){
                System.out.println(Thread.currentThread().getName()+"\t"+"result = " + v);
            }
        })
        // exceptionally: 同时感知异常,同时返回默认值
        .exceptionally(e->{
            e.printStackTrace();
            return null;
        });
        System.out.println(Thread.currentThread().getName()+"\t"+"over...");
        //主线程不要立即结束,否则CompletableFuture默认使用的线程池会立即关闭,暂停几秒
        try { TimeUnit.SECONDS.sleep(3);  } catch (InterruptedException e) {e.printStackTrace();}
    }
}

3.CompletableFuture创建方式

CompletableFuture有一个空参构造器,但是不推荐使用

CompletableFuture 提供了四个静态方法来创建一个异步操作

  1. runAsync方法不支持返回值
  2. supplyAsync可以支持返回值,我们一般用supplyAsync来创建
	//runAsync方法不支持返回值
	public static CompletableFuture<Void> runAsync(Runnable runnable)
	public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)
	//supplyAsync可以支持返回值
	public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
	public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)
@Test
public void testReturnVoid() throws ExecutionException, InterruptedException {
    CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(new Runnable() {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName()+"---- working");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    });
    System.out.println(completableFuture.get());
}

没有指定Executor的方法会使用ForkJoinPool.commonPool() 作为它的线程池执行异步代码。如果指定线程池,则使用指定的线程池运行。以下所有的方法都类同

@Test
public void testReturnParam() throws Exception {
    ExecutorService threadPool = Executors.newFixedThreadPool(3);
    CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(new Supplier<String>() {
        @Override
        public String get() {
            System.out.println(Thread.currentThread().getName() + "---- working");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return "hello SupplAsync";
        }
    },threadPool);
    System.out.println(completableFuture.get());
}

4. 小结和API介绍

img

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要同时运行两个CompletableFuture,可以使用`CompletableFuture.allOf()`方法来组合它们,并在一个新的CompletableFuture中等待它们的完成。下面是一个示例: ```java import java.util.concurrent.CompletableFuture; public class CompletableFutureExample { public static void main(String[] args) { CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> { // 第一个异步任务 return "Hello"; }); CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> { // 第二个异步任务 return "World"; }); CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(future1, future2); combinedFuture.thenRun(() -> { // 在两个任务都完成后执行的操作 String result1 = future1.join(); String result2 = future2.join(); System.out.println(result1 + " " + result2); }); // 等待两个任务完成 combinedFuture.join(); } } ``` 在上面的示例中,我们定义了两个CompletableFuture对象:`future1`和`future2`,它们分别表示两个异步任务。我们使用`CompletableFuture.allOf()`方法将它们组合在一起,并创建一个新的CompletableFuture对象`combinedFuture`来等待它们的完成。 然后,我们使用`combinedFuture.thenRun()`方法来指定在两个任务都完成后要执行的操作。在这个操作中,我们使用`future1.join()`和`future2.join()`来获取各自的结果,并进行打印。 最后,我们使用`combinedFuture.join()`方法等待所有任务完成。请注意,如果不等待任务完成,程序可能会在任务执行之前结束。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值