并发请求(对多个请求进行合并操作)
int totalSize = 100; int pageSize = 10; int totalPage = getTotalPage(totalSize, pageSize); ExecutorService executor = Executors.newFixedThreadPool(totalPage); long startTime = System.currentTimeMillis(); try { List<CompletableFuture<String>> list = new ArrayList<CompletableFuture<String>>(); for (int i = 0; i < totalPage; i++) { QueryRequest req = new QueryRequest(i, pageSize); list.add(CompletableFuture.supplyAsync(() -> { return QueryService.query(req); }, executor)); } CompletableFuture.allOf(list.toArray(new CompletableFuture[] {})).join(); StringBuilder sb = new StringBuilder(); for (CompletableFuture<String> ft : list) { String result = ft.get(10, TimeUnit.SECONDS); // 获取结果等待10s超时 sb.append(result); } System.err.println("main thread end====>"); System.err.println(sb.toString()); } catch (Exception e) { e.printStackTrace(); } executor.shutdown(); System.err.println(System.currentTimeMillis() - startTime);