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());//获取回调结果
    }
}
相关推荐
pshdhx_albert2 小时前
AI agent实现打字机效果
java·http·ai编程
沉鱼.443 小时前
第十二届题目
java·前端·算法
赫瑞3 小时前
数据结构中的排列组合 —— Java实现
java·开发语言·数据结构
周末也要写八哥5 小时前
多进程和多线程的特点和区别
java·开发语言·jvm
惜茶5 小时前
vue+SpringBoot(前后端交互)
java·vue.js·spring boot
杰克尼6 小时前
springCloud_day07(MQ高级)
java·spring·spring cloud
NHuan^_^8 小时前
SpringBoot3 整合 SpringAI 实现ai助手(记忆)
java·人工智能·spring boot
Mr_Xuhhh8 小时前
从ArrayList到LinkedList:理解链表,掌握Java集合的另一种选择
java·数据结构·链表
错把套路当深情8 小时前
Java 全方向开发技术栈指南
java·开发语言
han_hanker8 小时前
springboot 一个请求的顺序解释
java·spring boot·后端