• 利用completablefuture异步执行并发任务,并堵塞,全部完成后获取返回结果。


    代码很简单,简单来说也就是。先创建一个线程池类,然后再写一个并发任务执行就可以了。因为此并发任务是利用

    qvVerifyAsyncPool线程池处理的。

    核心为,

    1. //定义线程返回结果
    2. List> futures = new ArrayList>();

     然后执行多个并发,同时将任务返回结果添加到此结果集合中

    1. CompletableFuture future = CompletableFuture.supplyAsync(() -> {
    2. //任务
    3. return 1;
    4. },qvVerifyAsyncPool);

     添加并发任务结果

     futures.add(future);

     堵塞当所有的任务完成时返回结果

    1. //阻塞等待结果返回
    2. CompletableFuture allFutures = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]));
    3. List result = allFutures.thenApply(v -> futures.stream().map(CompletableFuture::join).collect(Collectors.toList())).join();

     完整代码如下:

    该线程池类代码如下:

    1. @Configuration
    2. @EnableAsync
    3. public class AsyncConfiguration {
    4. /**
    5. * 报告线程池--整个报告
    6. * @return ThreadPoolTaskExecutor
    7. */
    8. @Bean(name = "qvVerifyAsyncPool")
    9. public ThreadPoolExecutor QvVerifyAsyncPool(){
    10. return new ThreadPoolExecutor(
    11. //核心线程数
    12. qvCorePoolSize,
    13. //最大线程数
    14. qvMaxPoolSize,
    15. qvKeepAliveSeconds,
    16. TimeUnit.SECONDS,
    17. //队列大小
    18. new LinkedBlockingDeque(qvQueueCapacity),
    19. //定义线程名称
    20. new ThreadFactory() {
    21. private final AtomicInteger mThreadNum = new AtomicInteger(1);
    22. @Override
    23. public Thread newThread(Runnable r) {
    24. return new Thread(r, "qvVerifyAsyncPool-" + mThreadNum.getAndIncrement());
    25. }
    26. },
    27. //拒绝策略
    28. new ThreadPoolExecutor.AbortPolicy()
    29. );
    30. }
    31. }
    1. /**
    2. * 简单Java并行代码
    3. * @param
    4. */
    5. public List simpleParallel(){
    6. List> futures = new ArrayList<>();
    7. for (int i = 0; i <10 ; i++) {
    8. CompletableFuture future = CompletableFuture.supplyAsync(() -> {
    9. System.out.println("有返回值的异步任务"+Thread.currentThread().getName());
    10. try {
    11. Thread.sleep(3000);
    12. } catch (InterruptedException e) {
    13. e.printStackTrace();
    14. }
    15. return 1;
    16. },qvVerifyAsyncPool);
    17. futures.add(future);
    18. }
    19. // 使用allOf方法来表示所有的并行任务
    20. CompletableFuture allFutures = CompletableFuture.allOf(
    21. futures.toArray(new CompletableFuture[futures.size()]));
    22. // 下面的方法可以帮助我们获得所有子任务的处理结果
    23. CompletableFuture> finalResults = allFutures.thenApply(v ->
    24. futures.stream().map(CompletableFuture::join).collect(Collectors.toList())
    25. );
    26. List resultList = finalResults.join();
    27. System.out.println(resultList);
    28. return resultList;
    29. }

  • 相关阅读:
    JVM 内存溢出 java heap space
    HTML期末大学生网页设计作业----锤子手机 1页
    写进简历的软件测试项目实战经验(包含电商、银行、app等)
    每次重启完IDEA,application.properties文件里的中文变成?
    2023年亚太杯数学建模思路 - 复盘:光照强度计算的优化模型
    MySql 数据类型选择与优化
    JS中BOM编程:设置浏览器地址栏地址
    【手撕数据结构】二分查找(好多细节)
    红帽社区论坛
    AcWing 4. 多重背包问题 I 学习笔记
  • 原文地址:https://blog.csdn.net/qq_48964306/article/details/126619093