一、相关概念

  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());
} }

最新文章

  1. java多线程系类:JUC原子类:05之AtomicIntegerFieldUpdater原子类
  2. 移动WebApp利用Chrome浏览器进行调试
  3. http基础实战
  4. 重新想象 Windows 8 Store Apps (51) - 输入: 涂鸦板
  5. struts2.3.16所需的基本的jar包
  6. [Effective JavaScript 笔记]第23条:永远不要修改arguments对象
  7. Android客户端与服务器之间传递json数据
  8. Color the Ball[HDU1199]
  9. 【转】唱吧CEO陈华:创业四年,我积累的7点管理经验
  10. 使用命令xrandr设置当前系统的显示分辨率及显示的旋转脚本
  11. [PWA] 8.Unobtrusive update: Delete old cache and only keep one, hard refresh to let new SW to take control
  12. [Mugeda HTML5技术教程之8]添加行为
  13. SVN-TortoiseSVN安装和常用操作步骤
  14. (转)maven镜像路径配置
  15. LR-Controller 如何自定义显示虚拟用户状态
  16. jvm虚拟机分享课笔记
  17. Scala学习(五)---Scala中的类
  18. iOS 精简Controlelr代码的两个方法
  19. Navicat Premium 12连接Oracle时提示oracle library is not loaded的问题解决
  20. selenium常用命令

热门文章

  1. 《Java并发编程的艺术》笔记
  2. appcan 文件下载与预览
  3. Redis利用,攻击内网(ssrf)
  4. [Vue warn]: Error in render: &quot;TypeError: Cannot read property &#39;matched&#39; of undefined&quot; found in &lt;App&gt; at src/App.vue
  5. Java知识系统回顾整理01基础03变量07final关键字
  6. Python实现的数据结构与算法之基本搜索详解
  7. spring-boot-route(十二)整合redis做为缓存
  8. python数据清洗
  9. Ambari仓库安装教程
  10. 因果推理综述——《A Survey on Causal Inference》一文的总结和梳理