CompletableFuture

简介: CompletableFuture

CompletableFuture演示Future功能

public class CompeltableFutureUseDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName()+"--------come in");
            int result = ThreadLocalRandom.current().nextInt(10);
            try {
                TimeUnit.MILLISECONDS.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("--------1秒钟后出结果:"+result);
            return result;
        },threadPool);
        System.out.println(Thread.currentThread().getName()+"线程先去忙别的任务");
        System.out.println(completableFuture.get());
    }
}

演示完成一个阶段后将值穿个下一个阶段

public class CompeltableFutureUseDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        try{
            CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
                System.out.println(Thread.currentThread().getName()+"--------come in");
                int result = ThreadLocalRandom.current().nextInt(10);
                try {
                    TimeUnit.MILLISECONDS.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("--------1秒钟后出结果:"+result);
                return result;
            },threadPool).whenComplete((v,e)->{
                if(e==null){
                    System.out.println("------计算完成,更新系统updateValue:"+v);
                }
            }).exceptionally(e->{
                e.printStackTrace();
                System.out.println("异常情况:"+e.getCause()+"\t"+e.getMessage());
                return null;
            });
            System.out.println(Thread.currentThread().getName()+"线程先去忙别的任务");
        }catch (Exception e){
            e.printStackTrace();
        }finally{
            threadPool.shutdown();
        }
    }
}

image.png

演示异常

public class CompeltableFutureUseDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        try{
            CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
                System.out.println(Thread.currentThread().getName()+"--------come in");
                int result = ThreadLocalRandom.current().nextInt(10);
                try {
                    TimeUnit.MILLISECONDS.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("--------1秒钟后出结果:"+result);
                if(result>1){
                    int i = 10/0;
                }
                return result;
            },threadPool).whenComplete((v,e)->{
                if(e==null){
                    System.out.println("------计算完成,更新系统updateValue:"+v);
                }
            }).exceptionally(e->{
                e.printStackTrace();
                System.out.println("异常情况:"+e.getCause()+"\t"+e.getMessage());
                return null;
            });
            System.out.println(Thread.currentThread().getName()+"线程先去忙别的任务");
        }catch (Exception e){
            e.printStackTrace();
        }finally{
            threadPool.shutdown();
        }
    }
}

返回结果:

image.png

CompletableFuture的优点

  • 异步任务结束后,会自动回调某个对象的方法
  • 主线程设置好回调后,不再关心异步任务的执行,异步任务之间可以顺序执行
  • 异步任务出错时,会自动回调某个对象的方法
目录
相关文章
|
开发工具 git
深入探索Git的高级技巧与神奇操作(分支,高效合并)
深入探索Git的高级技巧与神奇操作(分支,高效合并)
661 0
IDEA激活笔记
IDEA2022版激活笔记
|
资源调度 监控 项目管理
信息系统项目管理师项目变更管理
信息系统项目管理师项目变更管理 项目变更管理的基本概念 项目变更产生的原因变更的常见原因: 项目变更分类 项目变更的含义 项目变更管理原则 变更管理组织机构与工作程序 组织机构 工作程序 项目变更管理的工作内容 严格控制项目变更申请的提交 变更控制 变更管理与其他项目管理要素的关系 版本发布和回退计划 软件版本发布前的准备 版本发布应急回退方案 版本发布和回退实施过程总结
519 0
|
安全 Android开发 C++
多个so中模板单例的多次实例化
在Android打包项目时,发现登录功能不能使用了,logcat中也没发现什么问题,最后一行一行log定位到了问题。原来是一个so文件中的构造函数被初始化二次!   这个单例是通过继承模板来实现的(暂时不考虑线程安全的问题) templateclass CSingleT{public:s...
1205 0
|
Web App开发 XML JSON
WebAPI返回数据类型解惑 以及怎样解决Extjs无法解析返回的xml
 最近开始使用WebAPI,上手很容易,然后有些疑惑   1.WebAPI默认返回什么数据类型,json还是xml?  2.怎么修改WebAPI的返回数据类型,我用IE浏览器请 求返回的数据都是JSON格式的,用Firefox和Chrome返回数据格式是XML,然后自己用HttpWebReque...
1097 0
|
11天前
|
存储 关系型数据库 分布式数据库
PostgreSQL 18 发布,快来 PolarDB 尝鲜!
PostgreSQL 18 发布,PolarDB for PostgreSQL 全面兼容。新版本支持异步I/O、UUIDv7、虚拟生成列、逻辑复制增强及OAuth认证,显著提升性能与安全。PolarDB-PG 18 支持存算分离架构,融合海量弹性存储与极致计算性能,搭配丰富插件生态,为企业提供高效、稳定、灵活的云数据库解决方案,助力企业数字化转型如虎添翼!
|
9天前
|
存储 人工智能 搜索推荐
终身学习型智能体
当前人工智能前沿研究的一个重要方向:构建能够自主学习、调用工具、积累经验的小型智能体(Agent)。 我们可以称这种系统为“终身学习型智能体”或“自适应认知代理”。它的设计理念就是: 不靠庞大的内置知识取胜,而是依靠高效的推理能力 + 动态获取知识的能力 + 经验积累机制。
342 130
|
9天前
|
存储 人工智能 Java
AI 超级智能体全栈项目阶段二:Prompt 优化技巧与学术分析 AI 应用开发实现上下文联系多轮对话
本文讲解 Prompt 基本概念与 10 个优化技巧,结合学术分析 AI 应用的需求分析、设计方案,介绍 Spring AI 中 ChatClient 及 Advisors 的使用。
430 130
AI 超级智能体全栈项目阶段二:Prompt 优化技巧与学术分析 AI 应用开发实现上下文联系多轮对话