前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ComplatableFuture初解使用

ComplatableFuture初解使用

作者头像
半月无霜
发布2024-02-25 10:16:49
1380
发布2024-02-25 10:16:49
举报
文章被收录于专栏:半月无霜半月无霜

ComplatableFuture初解使用

一、介绍

CompletableFuture是Java中的一个类,用于进行异步编程。它提供了一套强大的方法,可以方便地管理异步操作、处理结果和错误等。

二、方法

方法

功能

入参

出参

completedFuture(T value)

创建一个已经完成结果的CompletableFuture对象

runAsync(Runnable runnable)

启动异步任务

supplyAsync(Supplier<U> supplier)

启动异步任务

thenApply(Function<T, U> function)

转换一个CompletableFuture对象及内容

thenApplyAsync(Function<T, U> fn)

启动异步任务,转换一个CompletableFuture对象及内容

thenAccept(Consumer<T> consumer)

消费一个CompletableFuture对象的内容

thenAcceptAsync(Consumer<T> action, Executor executor

启动异步任务,消费一个CompletableFuture对象的内容

thenRun(Runnable runnable)

当之前的任务完成后,执行任务

thenRunAsync(Runnable action, Executor executor)

当之前的任务完成后,执行异步任务

thenCompose(Function<T, CompletableFuture<U>> function)

将一个CompletableFuture对象内容,转换为一个新的CompletableFuture对象

exceptionally(Function<Throwable, T> function)

当前面CompletableFuture对象的任务出现异常时,会进入此方法

handle(BiFunction<T, Throwable, U> biFunction)

当前面CompletableFuture对象的任务完成,或者出现异常时,会进入此方法

allOf(CompletableFuture<?>... cfs)

等内部所有CompletableFuture对象的任务完成,返回一个新的CompletableFuture对象

这些方法提供了灵活和强大的功能,可用于编写复杂的异步任务,并管理它们的结果和异常。

主要可以看到,只要方法名上包括Async的,都可以指定一个线程池,启动一个异步任务。

then开头的方法名,则可以认为是上一个任务结束后进行的任务调用。

三、示例使用

下面就是一些测试使用的例子了

这是一个输出打印工具类,里面有线程名信息

代码语言:javascript
复制
package com.banmoon.complatablefuture;

import cn.hutool.core.date.DateUtil;

import java.util.concurrent.TimeUnit;

public class ThreadUtil {

    public static void printThread(Object o) {
        System.out.println("线程名:[" + Thread.currentThread().getName() +  "] 时间:[" + DateUtil.now() + "]" + o);
    }

    public static void sleepSecond(long second) {
        try {
            TimeUnit.SECONDS.sleep(second);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

}

代码

代码语言:javascript
复制
package com.banmoon.complatablefuture;

import org.junit.Test;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CompletableFutureTest {

    public static final ExecutorService threadPool = Executors.newFixedThreadPool(5);

    @Test
    public void test01() {
        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
            ThreadUtil.printThread("测试");
            return "结果";
        });
        ThreadUtil.printThread("等待结果:" + completableFuture.join());
    }

    @Test
    public void test02() {
        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
            ThreadUtil.printThread("测试");
        });
        ThreadUtil.printThread("等待结果:" + completableFuture.join());
    }

    @Test
    public void test03() {
        CompletableFuture<String> completableFuture = CompletableFuture
                .completedFuture("结果")
                .thenApply(t -> {
                    ThreadUtil.printThread("测试1");
                    return t + "1";
                }).thenApplyAsync(t -> {
                    ThreadUtil.printThread("测试2");
                    return t + "2";
                }, threadPool);
        ThreadUtil.printThread("等待结果:" + completableFuture.join());
    }

    @Test
    public void test04() {
        CompletableFuture<Void> completableFuture = CompletableFuture
                .completedFuture("结果")
                .thenAccept(t -> {
                    ThreadUtil.printThread(t + "1");
                });
        CompletableFuture<Void> completableFuture2 = CompletableFuture
                .completedFuture("结果")
                .thenAcceptAsync(t -> {
                    ThreadUtil.printThread(t + "2");
                }, threadPool);
    }

    @Test
    public void test05() {
        CompletableFuture<Void> completableFuture = CompletableFuture
                .completedFuture("结果")
                .thenRun(() -> {
                    ThreadUtil.printThread("测试1");
                }).thenRunAsync(() -> {
                    ThreadUtil.printThread("测试2");
                }, threadPool);
    }

    @Test
    public void test06() {
        CompletableFuture<String> future = CompletableFuture
                .completedFuture("结果")
                .thenCompose(t -> {
                    ThreadUtil.printThread("测试");
                    return CompletableFuture.completedFuture(t + "1");
                });
        ThreadUtil.printThread(future.join());
    }

    @Test
    public void test07() {
        CompletableFuture<String> future = CompletableFuture
                .supplyAsync(() -> {
                    ThreadUtil.printThread("测试");
                    int i = 1 / 0;
                    return i + "";
                }, threadPool).exceptionally(e -> {
                    ThreadUtil.printThread("失败," + e.getMessage());
                    return "失败";
                });
        ThreadUtil.printThread(future.join());
    }

    @Test
    public void test08() {
        CompletableFuture<String> future = CompletableFuture
                .supplyAsync(() -> {
                    ThreadUtil.printThread("测试1");
                    return "结果";
                }, threadPool).handle((str, e) -> {
                    ThreadUtil.printThread("处理2");
                    return str + "2";
                });
        ThreadUtil.printThread(future.join());
    }

    @Test
    public void test10() {
        CompletableFuture<Void> completableFuture = CompletableFuture.allOf(CompletableFuture.supplyAsync(() -> {
            ThreadUtil.sleepSecond(1);
            ThreadUtil.printThread("测试1");
            return "测试1";
        }, threadPool), CompletableFuture.supplyAsync(() -> {
            ThreadUtil.sleepSecond(2);
            ThreadUtil.printThread("测试2");
            return "测试2";
        }, threadPool), CompletableFuture.supplyAsync(() -> {
            ThreadUtil.sleepSecond(3);
            ThreadUtil.printThread("测试3");
            return "测试3";
        }, threadPool)).thenRunAsync(() -> {
            ThreadUtil.printThread("测试4");
        }, threadPool);

        System.out.println(completableFuture.join());
    }

}

四、最后

我是半月,你我一同共勉!!!

本文参与?腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2024-02-24,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客?前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体分享计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • ComplatableFuture初解使用
    • 一、介绍
      • 二、方法
        • 三、示例使用
          • 四、最后
          相关产品与服务
          腾讯云服务器利旧
          云服务器(Cloud Virtual Machine,CVM)提供安全可靠的弹性计算服务。 您可以实时扩展或缩减计算资源,适应变化的业务需求,并只需按实际使用的资源计费。使用 CVM 可以极大降低您的软硬件采购成本,简化 IT 运维工作。
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
          http://www.vxiaotou.com