本文主要是介绍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);
}
}
运行结果
代码二
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异步编排的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!