CompletableFuture 使用详解

runAsync和supplyAsync方法,这个两个方法为CompletableFuture的主要使用方式,其主要作用给任务提供异步线程的操作方式

如何使用
CompletableFuture 提供了四个静态方法来创建一个异步操作。

public static CompletableFuture<Void> runAsync(Runnable runnable)
public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)

其中:
runAsyn方法不支持返回值

public class CompletableFutureTest02 {

    public CompletableFuture Test(){
        CompletableFuture future  = CompletableFuture.runAsync(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(">>>>print.."+i);
            }
        });
        return future;
    }


    public static void main(String[] args) {
        CompletableFutureTest02 test02 = new CompletableFutureTest02();
        test02.Test().join();
    }
}

supplyAsync可以支持返回值

public class CompletableFutureTest {
    public Integer Test() throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(()->{

            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            return 1;
        });

        CompletableFuture<Integer> future01 = CompletableFuture.supplyAsync(()->{

            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            return 1;
        });

        //使用get方法来获取返回值
        return future.get()+future01.get();
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFutureTest test = new CompletableFutureTest();

        Long begin = System.currentTimeMillis();
        System.out.println(">>>>>>>begin"+begin);
        /*
        在执行Test()方法是会启动future和future01两个线程
        并且两个线程执行完毕后获取到结果值才代表Test()方法执行结束
         */
        
        System.out.println(test.Test());
        Long end = System.currentTimeMillis();
        Long exec = end-begin;
        System.out.println(">>>>>>>end"+end+">>>>>>exec"+exec);
    }
}

计算结果完成时的回调方法

当CompletableFuture的计算结果完成,或者抛出异常的时候,可以执行特定的Action。主要是下面的方法:

public CompletableFuture<T> whenComplete(BiConsumer<? super T,? super Throwable> action)
public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action)
public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action, Executor executor)
public CompletableFuture<T> exceptionally(Function<Throwable,? extends T> fn)

参考:CompletableFuture 使用详解

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
CompletableFutureJava8引入的一个异步编程工具类,用于简化异步编程,提高代码可读性和可维护性。它可以让你在一个线程中进行异步编程,而无需显式地创建线程或使用回调函数。 CompletableFuture可以看作是对Future的扩展,它支持链式调用和组合操作,可以将多个CompletableFuture组合在一起,形成一个复杂的异步操作流程。它也提供了一些方法,比如thenApply、thenAccept、thenRun等,用于处理异步操作的结果。 在使用CompletableFuture时,我们可以将异步操作放在一个CompletableFuture对象中,然后通过链式调用的方式,将多个异步操作组合在一起,形成一个异步操作流程。当所有的异步操作都执行完毕后,可以使用CompletableFuture的get方法,获取异步操作的结果。 下面是一个使用CompletableFuture的示例代码: ```java CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> { // 异步操作 return 10; }).thenApplyAsync(result -> { // 处理异步操作结果 return result * 2; }).thenApplyAsync(result -> { // 处理异步操作结果 return result + 3; }); // 获取异步操作的结果 Integer result = future.get(); ``` 在上面的代码中,我们首先使用CompletableFuture的supplyAsync方法,将异步操作放在一个CompletableFuture对象中。然后通过thenApplyAsync方法,将两个处理异步操作结果的函数串联在一起,形成一个异步操作流程。最后通过get方法,获取异步操作的结果。 除了thenApplyAsync方法,CompletableFuture还提供了许多其他的方法,比如thenAcceptAsync、thenRunAsync、thenComposeAsync等,可以根据具体需求来选择使用。 总之,CompletableFuture是一个非常强大的异步编程工具类,可以让你写出更加简洁、易读、易维护的异步代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值