Java方法异步调用,并行

Java方法异步调用,并行

Java同一个方法在调用多个方法时默认是串行的方式,我的这个业务调用6个方法串行需要4秒左右,由于需要处理数据量比较多,需要优化

原来的逻辑:

//对象转换
List<JudicialUpdateItem> writUpdateItems = writService.queryListByPager(businessInfoSearch);

//对象转换
List<JudicialUpdateItem> discreditUpdateItems = discreditService.queryListByPager(businessInfoSearch);

//对象转换
List<JudicialUpdateItem> penaltiesUpdateItems = penaltiesService.queryListByPager(businessInfoSearch);

//对象转换
List<JudicialUpdateItem> stockFreezeItems = stockFreezeService.queryListByPager(businessInfoSearch);

//对象转换
List<JudicialUpdateItem> abnormalItems = abnormalService.queryListByPager(businessInfoSearch);

//对象转换
List<JudicialUpdateItem> illegalItems = illegalService.queryListByPager(businessInfoSearch);

优化过后大概需要1秒以内,效果明显

CompletableFuture<List<JudicialUpdateItem>> future1 = CompletableFuture.supplyAsync(() -> writService.queryListByPager(businessInfoSearch));
CompletableFuture<List<JudicialUpdateItem>> future2 = CompletableFuture.supplyAsync(() -> discreditService.queryListByPager(businessInfoSearch));
CompletableFuture<List<JudicialUpdateItem>> future3 = CompletableFuture.supplyAsync(() -> penaltiesService.queryListByPager(businessInfoSearch));
CompletableFuture<List<JudicialUpdateItem>> future4 = CompletableFuture.supplyAsync(() -> stockFreezeService.queryListByPager(businessInfoSearch));
CompletableFuture<List<JudicialUpdateItem>> future5 = CompletableFuture.supplyAsync(() -> abnormalService.queryListByPager(businessInfoSearch));
CompletableFuture<List<JudicialUpdateItem>> future6 = CompletableFuture.supplyAsync(() -> illegalService.queryListByPager(businessInfoSearch));

try {
    //获取并行执行任务结果
    List<JudicialUpdateItem> writUpdateItems = future1.get();
    List<JudicialUpdateItem> discreditUpdateItems = future2.get();
    List<JudicialUpdateItem> penaltiesUpdateItems = future3.get();
    List<JudicialUpdateItem> stockFreezeItems = future4.get();
    List<JudicialUpdateItem> abnormalItems = future5.get();
    List<JudicialUpdateItem> illegalItems = future6.get();
    //放入结果
    resultList.addAll(writUpdateItems);
    resultList.addAll(discreditUpdateItems);
    resultList.addAll(penaltiesUpdateItems);
    resultList.addAll(stockFreezeItems);
    resultList.addAll(abnormalItems);
    resultList.addAll(illegalItems);
}catch (Exception e){
    System.out.println("异常:"+e);
}

猜你喜欢

转载自blog.csdn.net/zhangxue_wei/article/details/103733685