首页 > 其他 > 详细

常用之juc

时间:2020-08-09 18:30:48      阅读:71      评论:0      收藏:0      [点我收藏+]

// 没有返回值的异步回调 CompletableFuture.runAsync
// get方法会阻塞
CompletableFuture<Void> completableFuture=CompletableFuture.runAsync(()->{
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"runAsync->Void");
});

System.out.println("Demo1.main 11111");
completableFuture.get();
System.out.println("Demo1.main 22222");

 

// 有返回值得异步回调 CompletableFuture.supplyAsync
// whenComplete 编译成功后的处理
// exceptionally 异常后的处理
// get方法会阻塞
CompletableFuture<Integer> uCompletableFuture = CompletableFuture.supplyAsync(() -> {
System.out.println(Thread.currentThread().getName() + "supplyAsync->Integer");
int i=10/0;
return 1024;
});
System.out.println("Demo1.main 11111");
Integer integer = uCompletableFuture.whenComplete((t, u) -> {
System.out.println("t=>"+t); // 正常情况下,返回结果
System.out.println("u=>"+u);
}).exceptionally((e) -> { //异常情况下的处理
System.out.println(e.getMessage());
return 233;
}).get();
System.out.println(integer);
System.out.println("Demo1.main 22222");

常用之juc

原文:https://www.cnblogs.com/windy13/p/13463641.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!