CompletableFuture多任务执行

/**

* @param reqList

* @param localUrl

* @param type    0:摄像头抓拍

* @return

*/

public static ListcapturePic(List reqList, String localUrl, Integer type)throws ExecutionException, InterruptedException {

List> capList =new ArrayList<>();

    List list =new ArrayList<>();

    if (CollectionUtils.isNotEmpty(reqList)) {

for (MdCameraInfoReq req : reqList) {

String picUrl ="";

            if (Consts.INT_ZERO.equals(type)) {

//开启线程

                CompletableFuture future = CompletableFuture.supplyAsync(() -> {

return CapturePicUtils.capturePic(req.getIp(), req.getPort(), req.getUserName(), req.getPwd(), req.getChannel(), localUrl);

                }, executorFinishWeighImgService);

                //抓图线程list

                capList.add(future);

            }else {

picUrl = CapturePicUtils.captureNvrPic(req, localUrl);

            }

if (StringUtils.isNotBlank(picUrl)) {

list.add(picUrl);

            }

}

}

List captures =new ArrayList<>();

    CompletableFuture completableFuture = CompletableFuture.allOf(capList.toArray(new CompletableFuture[capList.size()]));

    //阻塞,直到所有任务结束

    completableFuture.join();

    CompletableFuture> captureList = completableFuture.thenApply(returnFuture -> {

capList.forEach(future -> {

try {

if (Objects.nonNull(future.get(5, TimeUnit.SECONDS))) {

captures.add(future.get(5, TimeUnit.SECONDS));

                }else {

log.error("获取数据超时");

                }

}catch (InterruptedException e) {

log.error("终端异常:{}", e);

            }catch (ExecutionException e) {

log.error("capturePic执行异常:{}", e);

            }catch (TimeoutException e) {

log.error("capturePic超时:{}", e);

            }

});

        return captures;

    });

    List baseList = captureList.get().stream().collect(Collectors.toList());

    return baseList;

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容