JUC---09异步回调

一、相关概念

  Java的过程是阻塞的,因此要实现异步回调,需要多线程的支持。要实现回调,B函数在不知道A函数具体实现的情况下能够调用A函数,这是一种多态,需要接口来实现。下面实现一个简单的Java回调,模拟客户端向服务器发送请求,服务器在收到请求后执行客户端的函数(相当于服务器回过来通知客户端),整个过程异步执行

二、代码

  

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

public class Demo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        test02();
    }

    /**
     * 无结果异步回调
     *
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public static void test01() throws ExecutionException, InterruptedException {

        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "runAsync");
        });

        System.out.println("1111111111");
        //获取执行结果
        completableFuture.get();
    }

    /**
     * 有结果异步回调
     *
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public static void test02() throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "supplyAsync=>Integer");
            int i = 10 / 0;
            return 1024;

        });

        System.out.println(completableFuture.whenComplete((t, u) -> {
            System.out.println("t=>" + t); // 正常的返回结果
            System.out.println("u=>" + u); // 错误信息:
        }).exceptionally((e) -> {
            System.out.println(e.getMessage());
            return 233; // 可以获取到错误的返回结果
        }).get());
    }

}

 

posted @ 2020-06-06 15:01  Jenne  阅读(199)  评论(0)    收藏  举报