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());//获取回调结果
    }
}
相关推荐
camellias_4 小时前
【无标题】
java·tomcat
咸鱼2.04 小时前
【java入门到放弃】需要背诵
java·开发语言
椰猫子4 小时前
Java:异常(exception)
java·开发语言
win x5 小时前
Redis 使用~如何在Java中连接使用redis
java·数据库·redis
星晨雪海5 小时前
基于 @Resource 的支付 Service 多实现类完整示例
java·开发语言
阿维的博客日记6 小时前
什么是逃逸分析
java·juc
Ricky_Theseus6 小时前
C++右值引用
java·开发语言·c++
Rick19936 小时前
Java内存参数解析
java·开发语言·jvm
我是大猴子6 小时前
Spring代理类为何依赖注入失效?
java·后端·spring
勿忘,瞬间7 小时前
多线程之进阶修炼
java·开发语言