当前位置: 首页 > news >正文

java多线程场景3-并发处理和异步请求

概述

有一批企业要处理,线程池10个线程并发处理企业。同时每个企业要异步请求6个接口。
用两个线程池,一个处理企业,一个处理每个企业的异步请求。

代码

异步线程池

package com.zou.metabox.common.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;import java.util.concurrent.Executor;@Configuration
public class AsyncConfig {private static final int CORE_POOL_SIZE = 60;private static final int MAX_POOL_SIZE = 100;private static final int QUEUE_CAPACITY = 100;@Bean(name = "asyncExecutor")public Executor asyncExecutor() {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();executor.setCorePoolSize(CORE_POOL_SIZE);executor.setMaxPoolSize(MAX_POOL_SIZE);executor.setQueueCapacity(QUEUE_CAPACITY);executor.setThreadNamePrefix("asyncExecutor-");executor.initialize();return executor;}}

测试的controller接口

    @GetMapping("/start")public String startProcessing(@RequestParam int size) {return "Processing spend " + enterpriseService.processEnterprises(size);}

核心逻辑

并发处理企业,以及异步请求6个接口

package com.zou.metabox.service;import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.*;@Slf4j
@Service
public class EnterpriseService {@Resourceprivate EnterpriseApiService enterpriseApiService;// 使用懒加载方式创建线程池,避免在shutdown后无法重新使用private volatile ExecutorService executorService;private ExecutorService getExecutorService() {if (executorService == null || executorService.isShutdown()) {synchronized (this) {if (executorService == null || executorService.isShutdown()) {executorService = Executors.newFixedThreadPool(10);}}}return executorService;}public String processEnterprises(int size) {long batchStartTime = System.currentTimeMillis(); // 记录批次开始时间// 使用线程安全的队列ConcurrentLinkedQueue<Map<String, String>> list1 = new ConcurrentLinkedQueue<>();ConcurrentLinkedQueue<Map<String, String>> list2 = new ConcurrentLinkedQueue<>();ConcurrentLinkedQueue<Map<String, String>> list3 = new ConcurrentLinkedQueue<>();ConcurrentLinkedQueue<Map<String, String>> list4 = new ConcurrentLinkedQueue<>();ConcurrentLinkedQueue<Map<String, String>> list5 = new ConcurrentLinkedQueue<>();ConcurrentLinkedQueue<Map<String, String>> list6 = new ConcurrentLinkedQueue<>();CountDownLatch countDownLatch = new CountDownLatch(size);ExecutorService executor = getExecutorService(); // 获取线程池实例for (int i = 1; i <= size; i++) {final int enterpriseId = i;executor.submit(() -> {long enterpriseStartTime = System.currentTimeMillis(); // 记录单个企业开始时间try {CompletableFuture<Map<String, String>> future1 = enterpriseApiService.callApi1(enterpriseId);CompletableFuture<Map<String, String>> future2 = enterpriseApiService.callApi2(enterpriseId);CompletableFuture<Map<String, String>> future3 = enterpriseApiService.callApi3(enterpriseId);CompletableFuture<Map<String, String>> future4 = enterpriseApiService.callApi4(enterpriseId);CompletableFuture<Map<String, String>> future5 = enterpriseApiService.callApi5(enterpriseId);CompletableFuture<Map<String, String>> future6 = enterpriseApiService.callApi6(enterpriseId);// 并发调用6个API,等待所有的api调用完成CompletableFuture.allOf(future1, future2, future3, future4, future5, future6).join();// 在所有异步请求完成后,再写入列表list1.add(future1.join());list2.add(future2.join());list3.add(future3.join());list4.add(future4.join());list5.add(future5.join());list6.add(future6.join());long enterpriseEndTime = System.currentTimeMillis();log.info("Finished processing enterprise: {}, Time taken: {}ms", enterpriseId, (enterpriseEndTime - enterpriseStartTime));} catch (InterruptedException e) {log.error("出错:{}", e.getMessage(), e);} finally {countDownLatch.countDown();}});}try {countDownLatch.await();} catch (InterruptedException e) {log.error("出错:{}", e.getMessage(), e);}// log打印每个列表的数量log.info("list1 size: {}", list1.size());log.info("list2 size: {}", list2.size());log.info("list3 size: {}", list3.size());log.info("list4 size: {}", list4.size());log.info("list5 size: {}", list5.size());log.info("list6 size: {}", list6.size());long batchEndTime = System.currentTimeMillis();long time = batchEndTime - batchStartTime;log.info("Batch processing completed. Total time: {} ms", time);return time/1000 + " s";}
}

异步接口

package com.zou.metabox.service;import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;@Service
public class EnterpriseApiService {@Async("asyncExecutor")public CompletableFuture<Map<String, String>> callApi1(int enterpriseId) throws InterruptedException {// 模拟API调用Thread.sleep(1000); // 假设每个API需要1秒响应时间Map<String, String> map = new HashMap<>();map.put("function name", enterpriseId + " callApi1");return CompletableFuture.completedFuture(map);}@Async("asyncExecutor")public CompletableFuture<Map<String, String>> callApi2(int enterpriseId) throws InterruptedException {// 模拟API调用Thread.sleep(1000); // 假设每个API需要1秒响应时间Map<String, String> map = new HashMap<>();map.put("function name", enterpriseId + " callApi2");return CompletableFuture.completedFuture(map);}@Async("asyncExecutor")public CompletableFuture<Map<String, String>> callApi3(int enterpriseId) throws InterruptedException {// 模拟API调用Thread.sleep(1000); // 假设每个API需要1秒响应时间Map<String, String> map = new HashMap<>();map.put("function name", enterpriseId + " callApi3");return CompletableFuture.completedFuture(map);}@Async("asyncExecutor")public CompletableFuture<Map<String, String>> callApi4(int enterpriseId) throws InterruptedException {// 模拟API调用Thread.sleep(1000); // 假设每个API需要1秒响应时间Map<String, String> map = new HashMap<>();map.put("function name", enterpriseId + " callApi4");return CompletableFuture.completedFuture(map);}@Async("asyncExecutor")public CompletableFuture<Map<String, String>> callApi5(int enterpriseId) throws InterruptedException {// 模拟API调用Thread.sleep(1000); // 假设每个API需要1秒响应时间Map<String, String> map = new HashMap<>();map.put("function name", enterpriseId + " callApi5");return CompletableFuture.completedFuture(map);}@Async("asyncExecutor")public CompletableFuture<Map<String, String>> callApi6(int enterpriseId) throws InterruptedException {// 模拟API调用Thread.sleep(1000); // 假设每个API需要1秒响应时间Map<String, String> map = new HashMap<>();map.put("function name", enterpriseId + " callApi6");return CompletableFuture.completedFuture(map);}}

测试接口

传入参数10
在这里插入图片描述
传入参数100
在这里插入图片描述


文章转载自:

http://M1coUwgX.ydzLy.cn
http://XVqmgnDw.ydzLy.cn
http://HrgB35q3.ydzLy.cn
http://bSgrraIj.ydzLy.cn
http://tuIxBD7c.ydzLy.cn
http://owTCV8Kq.ydzLy.cn
http://fhzw8teY.ydzLy.cn
http://YTeqcAlv.ydzLy.cn
http://X3empdI4.ydzLy.cn
http://h1zKDuge.ydzLy.cn
http://G4gopwp5.ydzLy.cn
http://Tzg94wEn.ydzLy.cn
http://XELBvetu.ydzLy.cn
http://O5No3hrT.ydzLy.cn
http://JfJOIygz.ydzLy.cn
http://xEWUZu80.ydzLy.cn
http://ObT007ca.ydzLy.cn
http://l42BqUJZ.ydzLy.cn
http://HnvVQah0.ydzLy.cn
http://V4QSKmc3.ydzLy.cn
http://vfAH6K9L.ydzLy.cn
http://ML5tXU2e.ydzLy.cn
http://JJPq08tL.ydzLy.cn
http://rmU4QDYb.ydzLy.cn
http://R9kQ3g0N.ydzLy.cn
http://Y4nepzJG.ydzLy.cn
http://Aj0NHNQL.ydzLy.cn
http://PdpLAkrc.ydzLy.cn
http://eONPrIzK.ydzLy.cn
http://Ht4OpMWH.ydzLy.cn
http://www.dtcms.com/a/376870.html

相关文章:

  • <uniapp><指针组件>基于uniapp,编写一个自定义箭头指针组件
  • 新手向:中文语言识别的进化之路
  • Jakarta EE 课程 --- 微型资料投递与分发(Mini Drop-off Box)
  • 【船类】监控录像下船舶类别检测识别数据集:近7k图像,6类,yolo标注
  • 《UE5_C++多人TPS完整教程》学习笔记51 ——《P52 使用我们的瞄准偏移(Using Our Aim Offsets)》
  • 腾讯云远程桌面连接不上?5步排查法解决RDP连接失败
  • ffplay播放pcm
  • 计算机毕业设计 基于Hadoop的B站数据分析可视化系统的设计与实现 Python 大数据毕业设计 Hadoop毕业设计选题【附源码+文档报告+安装调试】
  • 【Halcon 】Halcon 裁剪尺寸的像素陷阱全解析:为什么要 -0.5,为什么要 -1,而圆却不用?
  • 机器视觉质检数据融合PLM:产品缺陷根因分析新范式
  • 【超详细图文教程】2025年最新Win10 系统安装 MySQL 教程
  • 医疗行业面临的网络安全挑战及应对策略
  • JVM CMS垃圾回收器深度解析
  • 鸿蒙Next ArkWeb进程解析:多进程架构如何提升Web体验
  • Credo发布专为低功耗、高带宽与超低时延的AI网络打造的Bluebird 1.6T光DSP芯片
  • Shell 循环语句与函数全解析
  • Zookeeper核心知识全解:节点类型、集群架构与选举机制
  • Android 项目中 Gradle 配置实战:多渠道打包、签名配置、版本管理
  • 新手向:实现验证码程序
  • 【小程序】微信小程序隐私协议
  • LeetCode 刷题【71. 简化路径】
  • 【LeetCode 每日一题】1493. 删掉一个元素以后全为 1 的最长子数组——(解法一)预处理
  • Java代理模式详解
  • 【论文阅读】MEDDINOV3:如何调整视觉基础模型用于医学图像分割?
  • 超声波探伤的所用到的频段?
  • 关于ping不通,如何排查?
  • const allImages = { ...leftCategoryImages, ...rightCategoryImages }; 是是什么用法
  • 论文阅读:arxiv 2023 Large Language Models are Not Stable Recommender Systems
  • Transformer系列 | Pytorch复现Transformer
  • 神经网络常见层速查表