JUC并发编程学习笔记(十四)异步回调

异步回调

Future设计的初衷:对将来的某个事件的结果进行建模

在Future类的子类中可以找到CompletableFuture,在介绍中可以看到这是为非异步的请求使用一些异步的方法来处理

点进具体实现类中,查看方法,可以看到CompletableFuture中的异步内部类,里面是实现的异步方法

以及一些异步方法

通过CompletableFuture可以实现与Ajax一样的异步调用。

java 复制代码
package org.example.asyn;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/*
 * 异步调用:CompletableFuture
 * //异步执行
 * //成功回调
 * //失败回调
 * */
public class Demo01 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableHasReturn() ;

    }

    public static void CompletableNotReturn() throws ExecutionException, InterruptedException {
        //没有返回值的异步回调
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {

            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("执行异步请求完毕");

        });


        for (int i = 0; i < 5; i++) {

            TimeUnit.SECONDS.sleep(1);
            System.out.println(i);


        }
        //获取回调结果
        future.get();
    }

    public static void CompletableHasReturn() throws ExecutionException, InterruptedException {
        //有返回值的异步回调
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            int i = 10/0;
            return 1024;
        });
        System.out.println(future.whenComplete((t, u) -> {//编译
            System.out.println("t:" + t);//t是正常的返回结果
            System.out.println("u:" + u);//u是报错信息
        }).exceptionally((e) -> {//编译异常 /Exception e
            e.printStackTrace();
            return 123;//异常返回结果
        }).get());//获取回调结果
    }
}
相关推荐
Full Stack Developme1 分钟前
Spring Boot 事务管理完整教程
java·数据库·spring boot
城管不管29 分钟前
前后端远程协作
java
青云计划33 分钟前
Feed流
java·后端·spring
java1234_小锋1 小时前
String、StringBuilder、StringBuffer的区别?
java·开发语言
星原望野1 小时前
JAVA集合:List、Set和Map
java·开发语言·list·set·map·集合
2601_957787581 小时前
星链引擎矩阵系统:插件化多平台 API 网关与账号级隔离技术实践
java·矩阵·插件化架构
多敲代码防脱发2 小时前
Spring进阶(容器实现)
java·开发语言·后端·spring
星辰_mya2 小时前
彩云之上——[特殊字符]的架构师
java·后端·微服务·面试·架构
phltxy2 小时前
Redis 主从复制
java·数据库·redis
Full Stack Developme2 小时前
Spring-Core 解析
java·spring·rpc