• 异步回调


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

    1. package com.kuang.future;
    2. import com.kuang.pc.C;
    3. import java.util.concurrent.CompletableFuture;
    4. import java.util.concurrent.ExecutionException;
    5. import java.util.concurrent.TimeUnit;
    6. import java.util.function.Function;
    7. /**
    8. * 异步调用:CompletableFuture
    9. * 异步执行
    10. * 成功回调
    11. * 失败回调
    12. *
    13. */
    14. public class Demo01 {
    15. public static void main(String[] args) throws ExecutionException, InterruptedException {
    16. // //发起一个请求 无返回值 void
    17. // CompletableFuture completableFuture=CompletableFuture.runAsync(()->{
    18. // try {
    19. // TimeUnit.SECONDS.sleep(2);
    20. // } catch (InterruptedException e) {
    21. // e.printStackTrace();
    22. // }
    23. // System.out.println(Thread.currentThread().getName()+"->runAsync()->void");
    24. // });
    25. // System.out.println("11111");
    26. // completableFuture.get();//获取阻塞执行结果
    27. //有返回值的 supplyAsync 异步回调
    28. //ajax,成功与失败的回调
    29. // 返回的是错误信息
    30. CompletableFuture completableFuture= CompletableFuture.supplyAsync(()->{
    31. System.out.println(Thread.currentThread().getName()+"->supplyAsync()->Integer");
    32. int i=1/0;
    33. return 1024;
    34. });
    35. System.out.println(completableFuture.whenComplete((t, u) -> {
    36. System.out.println("t=>" + t);//正常的返回结果
    37. System.out.println("u=>" + u);//有错误打印错误信息:u=>java.util.concurrent.CompletionException: java.lang.ArithmeticException: / by zero
    38. }).exceptionally(e -> {
    39. System.out.println(e.getMessage());
    40. return 233;//可以获取到错误的返回结果
    41. }).get());
    42. /**
    43. * success code 200
    44. * error code 404 500
    45. */
    46. }
    47. }

  • 相关阅读:
    Spring Boot面试系列-01
    什么是 .gitkeep ?
    CentOS安装Docker
    大结局:奥特曼等人将加入微软
    Spring-IOC控制反转
    Linux系统性能监测工具——网络/进程
    Deep Learning-Based Object Pose Estimation:A Comprehensive Survey
    Node.js精进(7)——日志
    Linux下gdb调试工具用法
    MaxScale读写分离
  • 原文地址:https://blog.csdn.net/qq_53374893/article/details/133230410