CompletableFuture异步编排

代码一

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

运行结果

CompletableFuture异步编排

代码二

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异步编排

上一篇:并发编程之:异步调用获取返回值


下一篇:多线程与单线程的效率对比