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());//获取回调结果
    }
}
相关推荐
考虑考虑8 小时前
JDK25模块导入声明
java·后端·java ee
_小马快跑_9 小时前
Java 的 8 大基本数据类型:为何是不可或缺的设计?
java
Re_zero12 小时前
线上日志被清空?这段仅10行的 IO 代码里竟然藏着3个毒瘤
java·后端
洋洋技术笔记12 小时前
Spring Boot条件注解详解
java·spring boot
程序员清风1 天前
程序员兼职必看:靠谱软件外包平台挑选指南与避坑清单!
java·后端·面试
皮皮林5511 天前
利用闲置 Mac 从零部署 OpenClaw 教程 !
java
华仔啊2 天前
挖到了 1 个 Java 小特性:var,用完就回不去了
java·后端
SimonKing2 天前
SpringBoot整合秘笈:让Mybatis用上Calcite,实现统一SQL查询
java·后端·程序员
日月云棠2 天前
各版本JDK对比:JDK 25 特性详解
java
用户8307196840822 天前
Spring Boot 项目中日期处理的最佳实践
java·spring boot