Java 多线程工作之CompletableFuture.runAsync案例

public static void main(String[] args) {
          
   
        //runAsync 方法没返回值    用upplyAsync的话就有返回值
        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(()->{
          
   
                //大区 + 数量
                List<Map<String, Object>> regionNum = null;
                try {
          
   
                    regionNum = ddpSaleReportService.getRegionNum(params);
                } catch (ParseException e) {
          
   
                    e.printStackTrace();
                }
                ret.put("regionAndNum",regionNum);
            }).exceptionally(exception->{
          
   
                log.error("xx方法获取大区+数量异常:{}",exception.getMessage());
                return null;
            });
            CompletableFuture<Void> completableFuture1 = CompletableFuture.runAsync(()->{
          
   
                //车系 + 数量
                List<Map<String, Object>> carSeriesList = null;
                try {
          
   
                    carSeriesList = ddpSaleReportService.carSeriesProportionNum(params);
                } catch (ParseException e) {
          
   
                    e.printStackTrace();
                }
                ret.put("carSeries",carSeriesList);
            }).exceptionally(exception->{
          
   
                log.error("xx方法获取车系+数量异常:{}",exception.getMessage());
                //如果需要ret.put("carSeries",null);这种操作就在这里写
                ret.put("carSeries",null);
                //completableFuture1任务返回什么 这里就返回什么
                return null;
            });
            //扩展:这个方法还可以以线程池的方式去执行这条任务,避免频繁的创建线程 销毁线程造成性能损失
            //CompletableFuture test = CompletableFuture.runAsync(()->{},线程池);
            //由于任务1任务2是异步的,此处可以继续写业务代码,上面两条任务执行不影响主线程继续执行后面的业务代码

            //get()方法是等待任务1,任务2完成后在返回。任务1任务2执行期间会阻塞在这里
            CompletableFuture.allOf(completableFuture,completableFuture1).get();
           //后面继续写方法
    }
经验分享 程序员 微信小程序 职场和发展