CompletableFuture
Posted moris5013
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CompletableFuture相关的知识,希望对你有一定的参考价值。
public class CompletableFutureTest { public static void main(String[] args) throws Exception { // test2(); // test1(); // test3(); test4(); } //采用了callable+ future方式 public static void test1() throws Exception { ExecutorService executor = Executors.newCachedThreadPool(); Future<String> result = executor.submit(()->{ //模拟执行耗时任务 System.out.println("task doing..."); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } //返回结果 return "result"; }); //这里只是将空闲的线程中断,将线程池的状态改为shutdown,不能继续往线程池中添加任务 executor.shutdown(); System.out.println("task运行结果" + result.get()); } //采用了competableFuture方式 public static void test2() throws Exception { //supplyAsync内部使用ForkJoinPool线程池执行任务 CompletableFuture<String> completableFuture=CompletableFuture.supplyAsync(()->{ //模拟执行耗时任务 System.out.println("task doing..."); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } //返回结果 return "result"; }); System.out.println("计算结果:"+completableFuture.get()); } public static void test3() throws Exception { CompletableFuture<Integer> completableFuture = new CompletableFuture<>(); new Thread(() -> { System.out.println("task doing..."); try { Thread.sleep(5_000); // int i = 1/0; completableFuture.complete(10);//如果价格计算正常结束,完成Future操作并设置商品价格 } catch (Exception ex) { completableFuture.completeExceptionally(ex);//否则抛出导致失败的异常,完成这次Future操作 } }).start(); System.out.println("计算结果:"+completableFuture.get()); } //一个线程计算奇数和,一个线程计算偶数和,main线程将他们相加 public static void test4() throws ExecutionException, InterruptedException { CompletableFuture<Integer> oddNumber = CompletableFuture.supplyAsync(()->{ try { System.out.println("开始计算奇数和 ..."); Thread.sleep(3_000); System.out.println("结束计算奇数和 ..."); } catch (InterruptedException e) { e.printStackTrace(); } return 1+3+5+7+9; }); CompletableFuture<Integer> evenNumber = CompletableFuture.supplyAsync(()->{ try { System.out.println("开始计算偶数和 ..."); Thread.sleep(5_000); System.out.println("结束计算偶数和 ..."); } catch (InterruptedException e) { e.printStackTrace(); } return 2+4+6+8; }); long startTime = System.currentTimeMillis(); CompletableFuture<Integer> resultFuturn = oddNumber.thenCombine(evenNumber,(odd,even)->{ return odd + even; }); System.out.println("==============="); System.out.println("运行结果是:"+resultFuturn.get()+" 总共耗时:"+ (System.currentTimeMillis()-startTime) +"毫秒"); } }
以上是关于CompletableFuture的主要内容,如果未能解决你的问题,请参考以下文章
CompletableFuture异步编排(线程串行化代码示例)
CompletableFuture异步编排(计算完成回调代码示例)