CompletableFuture多个异步任务并行获取返回值实现
private static void man() throws ExecutionException, InterruptedException { long startTime = System.currentTimeMillis(); Man man = new Man(); CompletableFuture<String> future1 = CompletableFuture.supplyAsync(CompletableFutureDemo::name, threadPool); CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(CompletableFutureDemo::age, threadPool); CompletableFuture<String> future3 = CompletableFuture.supplyAsync(CompletableFutureDemo::sex, threadPool); CompletableFuture<Void> completableFuture1 = future1.thenAccept(man::setName); CompletableFuture<Void> completableFuture2 = future2.thenAccept(man::setAge); CompletableFuture<Void> completableFuture3 = future3.thenAccept(man::setSex); CompletableFuture<Void> completableFuture = CompletableFuture.allOf(completableFuture1, completableFuture2, completableFuture3); completableFuture.join(); System.out.println(man); threadPool.shutdown(); System.out.println("耗时:"+(System.currentTimeMillis()-startTime)/1000+"s"); }
private static String name(){ try { Thread.sleep(6000); } catch(Exception e) { e.printStackTrace(); } return "ZZZ"; } private static Integer age(){ try { Thread.sleep(4000); } catch(Exception e) { e.printStackTrace(); } return 18; } private static String sex(){ try { Thread.sleep(3000); } catch(Exception e) { e.printStackTrace(); } return "男"; }
耗时为最长的那个方法的时间,大大节省了时间
上一篇:
通过多线程提高代码的执行效率例子
下一篇:
seata分布式事务的异常