并发请求合并返回实例
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.UUID; import java.util.concurrent.*; import java.util.stream.Collectors; import java.util.stream.IntStream; public class App3 { static Logger log = LoggerFactory.getLogger(App3.class); static int coreSize = getDefaultCoreSize(); static int maxSize = coreSize * 2; static int keepAliveSeconds = 60; static BlockingQueue<Runnable> workQueue = new LinkedBlockingDeque<>(); static final ExecutorService executorService = new ThreadPoolExecutor(coreSize, maxSize, keepAliveSeconds, TimeUnit.SECONDS, workQueue ); public static void main(String[] args) throws Exception { log.info("开始执行"); List<Future<List<String>>> tasks = new ArrayList<>(); for (int i = 1; i <= 20; i++) { final int pageIdx = i; tasks.add(executorService.submit(() -> list(pageIdx))); } List<String> result = new ArrayList<>(1000); for (int i = 0; i < tasks.size(); i++) { result.addAll(tasks.get(i).get()); } log.info("结果:{}",result.size()); log.info("结果:{}",result); } private static List<String> list(int size) { int ms = ThreadLocalRandom.current().nextInt(100, 999); mySleep(ms); return IntStream.range(0, size) .mapToObj(p -> UUID.randomUUID().toString()) .collect(Collectors.toList()); } private static int getDefaultCoreSize() { return 2 * Runtime.getRuntime().availableProcessors(); } private static void mySleep(int millsecond) { try { Thread.sleep(millsecond); } catch (InterruptedException eax) { eax.printStackTrace(); } } }