首页 > 其他 > 详细

CompletableFuture异步编排

时间:2021-08-24 09:47:35      阅读:17      评论:0      收藏:0      [点我收藏+]

代码一

public class ThreadTest {

	public static ExecutorService executor = Executors.newFixedThreadPool(10);
	
	public static void main(String[] args) throws Exception {
		System.out.println("main---start");
//		CompletableFuture.runAsync(()->{
//			System.out.printf("当前线程  %d \n",Thread.currentThread().getId());
//			int i = 10/2;
//			System.out.printf("运行结果:%d",i);
//		}, executor);
		CompletableFuture<Integer> future = CompletableFuture.supplyAsync(()->{
			System.out.printf("当前线程  %d \n",Thread.currentThread().getId());
			int i = 10/0;
			System.out.printf("运行结果:%d \n",i);
			return i;
		}, executor).whenComplete((result,exception)->{
			//能得到异常信息,没法修改返回数据
			System.out.println("异步任务成功完成了...\n结果是 " + result + "\n异常是:" + exception);
		}).exceptionally(throwable -> {
			//可以感知异常,同时返回默认值
			return 777;
		});
		Integer result = future.get();
		System.out.printf("main---end... 结果是:%d ",result);
	}	
}

运行结果

技术分享图片

代码二

public class ThreadTest {

	public static ExecutorService executor = Executors.newFixedThreadPool(10);
	
	public static void main(String[] args) throws Exception {
		System.out.println("main---start");
		CompletableFuture<Integer> future = CompletableFuture.supplyAsync(()->{
			System.out.printf("当前线程  %d \n",Thread.currentThread().getId());
			int i = 10/0;
			System.out.printf("运行结果:%d \n",i);
			return i;
			//handle比whenComplete更强大,可以处理结果
		}, executor).handle((result,exception)->{
			if(result != null) {
				return result*2;
			}
			if(exception != null) {
				return 1990;
			}
			return -1;
		});
		Integer result = future.get();
		System.out.printf("main---end... 结果是:%d ",result);
	}	
}

运行结果

技术分享图片

CompletableFuture异步编排

原文:https://www.cnblogs.com/kaka-qiqi/p/15178188.html

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