参考: https://blog.csdn.net/teachy/article/details/104971814
创建线程池:
/** * 自定义线程池 * int corePoolSize, 核心线程数 = CPU核数 * int maximumPoolSize,最大线程数 = CPU核数 * 2 * long keepAliveTime, 等待时间,线程池线程 > 核心线程数,没有新任务等待keepAliveTime之后销毁 * TimeUnit unit, * BlockingQueue<Runnable> workQueue, 任务队列使用ArrayBlockingQueue,固定40长度 * RejectedExecutionHandler handler,饱和策略: CallerRunsPolicy: 不抛弃任务,也不抛异常,调用执行自己的线程运行任务 */ public static ExecutorService executor = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), Runtime.getRuntime().availableProcessors() * 2, 10L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(40),new ThreadPoolExecutor.CallerRunsPolicy());
具体多任务:
public Map<String, Object> routeVehicles(LogisticsTransportBillInfoInDTO billInfoInDTO) { long startTime = System.currentTimeMillis(); Map<String, Object> result = new HashMap<>(); MapTrack mapTrack = new MapTrack(); List list = new ArrayList(); CompletableFuture<String>[] completableFutures = new CompletableFuture[billInfoInDTO.getVersion()]; for (int i = 0; i < billInfoInDTO.getVersion(); i++) { final String vno = "陕YH0008" ; // 异步执行任务 CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { // 车牌号码 mapTrack.setVno(vno); mapTrack.setVco(2); mapTrack.setStartAreaCode("431102"); mapTrack.setEndAreaCode("450324"); //多个任务 return sinoiovRemote.transTimeManage(mapTrack); },executor); completableFutures[i] = future; } try { CompletableFuture<Void> allOf = CompletableFuture.allOf(completableFutures); //等待所有结果完成 allOf.get(); for (int i = 0; i < completableFutures.length; i++) { if (completableFutures[i] != null){ // 拿到结果 String res = completableFutures[i].get(); if (ObjectUtil.isNotEmpty(res)){ list.add(JSONUtil.toJsonStr(res)); }else { list.add(mapTrack); } } } }catch (Exception e){ e.printStackTrace(); }finally { //executor.shutdown(); } result.put("sinoiovList",list); long timeout = System.currentTimeMillis() - startTime; System.out.println(timeout); logger.info("程序耗时: " + timeout); return result; }
代码解释:
CompletableFuture.supplyAsync()
Async 异步执行方法
CompletableFuture<Void> allOf = CompletableFuture.allOf(completableFutures);
//同时执行多个任务
CompletableFuture.allOf()
//等待所有结果完成 allOf.get();
标签:异步,allOf,completableFutures,mapTrack,编排,线程,new,CompletableFuture,多任务 From: https://www.cnblogs.com/yxgmagic/p/17409198.html