线程池使用方法记录
使用线程池ThreadPoolExecutor,ForkJoinPool 等待所有线程都完成后再返回数据 ThreadPoolExecutor 具体代码public ListForkJoinPool 具体代码getGoodPrice(List skuPageNoList) { ArrayList goodsPriceDTOS = new ArrayList<>(); //第三方接口最多同时查100条数据,因此按数量100分批次 int size = skuPageNoList.size(); int count = (100+ size - 1)/100; ThreadPoolExecutor executor = new ThreadPoolExecutor(10,16,60,TimeUnit.SECONDS,new linkedBlockingQueue<>(),new ThreadPoolExecutor.CallerRunsPolicy()); for (int i = 0; i < count; i++) { String skuString = skuPageNoList.subList(i * 100, (Math.min((i + 1) * 100, size))).stream().map(SkuPageNo::getSkuNo).map(String::valueOf).collect(Collectors.joining(",")); executor.submit(()->{//具体业务代码});} executor.shutdown(); try { //当shutdown()请求发送后, 要求等待所有线程都完成 任务后才能关闭线程 executor.awaitTermination(1, TimeUnit.HOURS); } catch (InterruptedException e) { e.printStackTrace(); } return goodsPriceDTOS; }
java8 中parallelStream使用了ForkJoinPool 线程池,默认的核心线程数等于CPU的核数
//通过这两种方法可以自己设置线程数
//方法一
int numTasks = 10;
ForkJoinPool pool = new ForkJoinPool(numTasks);
//方法二
System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "10");
parallelStream中 使用自定义的线程数
ListjdGoodsDTOList = Collections.synchronizedList(new ArrayList<>()); //System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "9"); int numTasks = 10; ForkJoinPool pool = new ForkJoinPool(numTasks); //System.out.println("getCustomParallelism=" +pool.getParallelism()); pool.submit(() -> skuPageNoList.parallelStream().filter(Objects::nonNull).forEach(skuPageNo -> {/具体业务逻辑 })); pool.shutdown(); try { pool.awaitTermination(1, TimeUnit.HOURS); } catch (InterruptedException e) { e.printStackTrace(); } return jdGoodsDTOList;



