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

【多线程实例】

使用场景

拿到了一个商品的list,然后要循环list去获取每个商品的明细,由于调用api很依赖于网络,一个个执行速度慢,所以考虑使用线程去解决。

//根据机器id  获取 所有商品信息
public List<ProductResponse> productList(MachineConfigRequest.Code request) {//一次性查询数据库机器对应的商品listBoolQuery boolQuery = new BoolQuery();List<Query> queryList = new ArrayList<>();TermQuery termQuery1 = new TermQuery();termQuery1.setFieldName(ProductListConfigEnum.MACHINE_ID.getValue());termQuery1.setTerm(ColumnValue.fromString(request.getMachine_id()));queryList.add(termQuery1);boolQuery.setMustQueries(queryList);MachineCommonTableStore tableStore = new MachineCommonTableStore();SearchQuery searchQuery = new SearchQuery();searchQuery.setQuery(boolQuery);List<ProductResponse> searchResponse = tableStore.getRowList(searchQuery, ProductResponse.class, ModelEnum.PRODUCT_LIST.getModel(), ModelEnum.PRODUCT_LIST_INDEX.getModel());//根据机器id 和 获取所有的货道信息  key:slot value productInfoMap<String, ProductSlotInfo> map = this.getSlotInfo(request.getMachine_id());//转换为 key:productId value:slotListMap<String, List<ProductSlotInfo>> productSlotMap = this.getProductSlotList(map);//不需要更新货架图 直接返回库里面存的if (request.getLabel() == 0) {searchResponse.forEach(productResponse -> {//根据商品ID获取商品对应的货道listList<ProductSlotInfo> productSlotInfos = productSlotMap.get(productResponse.getProduct_id());//塞货道信息和库存this.setSlotAndQuantity(productResponse, productSlotInfos);});return searchResponse.parallelStream().sorted(Comparator.comparing(ProductResponse::getSlot_info)).collect(Collectors.toList());}//根据机器id 调用API 获取所有商品idMachineService service = new MachineService();List<ProductResponse> list = service.getProductInventory(request.getMachine_id(), ProductResponse.class);//循环对比 把之前已经配置过赏级的商品的id和赏级塞进去list.forEach(response -> searchResponse.stream().filter(row -> response.getProduct_id().equals(row.getProduct_id())).forEach(row -> {response.setId(row.getId());response.setMarket(row.getMarket());}));List<ProductResponse> responseList = Lists.newArrayList();if (CollectionUtils.isNotEmpty(list)) {ThreadPoolExecutor pool = new ThreadPoolExecutor(50, 50, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(100), (r, executor) -> {try {executor.getQueue().put(r);} catch (InterruptedException e) {e.printStackTrace();}});list.forEach(response -> pool.submit(() -> {//调用API 获取商品信息JSONObject object = new JSONObject();object.put(CeresonApiEnum.product_id.getValue(), response.getProduct_id());String json = RobotShopClient.callApiGet(CallMachineShopApiConstants.GET_PRODUCT_BY_ID, object.toJSONString());JSONObject jsonObject = JSON.parseObject(json);String data = jsonObject.getString(CeresonApiEnum.data.getValue());JSONObject js = JSON.parseObject(data);String productStr = js.getString(CeresonApiEnum.product.getValue());//把API获取的商品信息转换为ObjProductResponse productResponse = JSON.parseObject(productStr, ProductResponse.class);//根据商品ID获取商品对应的货道listList<ProductSlotInfo> productSlotInfos = productSlotMap.get(response.getProduct_id());//塞货道信息和库存this.setSlotAndQuantity(productResponse, productSlotInfos);responseList.add(productResponse);}));boolean allThreadsIsDone = pool.getTaskCount() == pool.getCompletedTaskCount();while (!allThreadsIsDone) {allThreadsIsDone = pool.getTaskCount() == pool.getCompletedTaskCount();}pool.shutdown();}return responseList.parallelStream().sorted(Comparator.comparing(ProductResponse::getSlot_info)).collect(Collectors.toList());
}
public PageResponse<AuctionListByUserIdResponse> getAuctionListByUserId(AuctionRequest.GetAuctionByUserId request) {AuctionTableStore auctionTableStore = new AuctionTableStore();List<Query> list = new ArrayList<>();BoolQuery boolQuery = new BoolQuery();BoolQuery shouldQuery = new BoolQuery();List<Sort.Sorter> sorter = TableStoreTemplate.getSorter(request.getSort());PageResponse<AuctionListByUserIdResponse> pageResponse = new PageResponse<>();try {pageResponse = auctionTableStore.queryAll(request.getNextToken(), sorter, boolQuery, request.getLimit(),AuctionListByUserIdResponse.class);} catch (Exception e) {log.error("getAuctionList failed exception = {}", e);throw new BaseException(ResponseCode.Bad_Request.getCode(), "查询失败!");}List<AuctionListByUserIdResponse> auctionListByUserIdResponses = pageResponse.getData();if (null != auctionListByUserIdResponses && auctionListByUserIdResponses.size() > 0) {ThreadPoolExecutor pool = new ThreadPoolExecutor(auctionListByUserIdResponses.size(), auctionListByUserIdResponses.size(), 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), new RejectedExecutionHandler() {@Overridepublic void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {try {executor.getQueue().put(r);} catch (InterruptedException e) {e.printStackTrace();}}});String robotSign = "##robot";auctionListByUserIdResponses.forEach(response -> {pool.submit(new Runnable() {@Overridepublic void run() {String sellerId = response.getSellerId();String buyerId = response.getBuyerId();String auctionId = response.getId();String twr = "";/* 处理是否为机器人 robotSign */if (buyerId.endsWith(robotSign) || sellerId.endsWith(robotSign)) {twr = "是";} else {twr = "否";}response.setWhetherRobot(twr);response.setAuctionGoodsList(getGoodsRangeByAuctionId(sellerId, auctionId, DeleteFlagEnum.DELETE));response.setAuctionBidGoodsList(getGoodsRangeByAuctionId(buyerId, auctionId, DeleteFlagEnum.DELETE));response.setCostPrice(getTotalCostPrice(response.getAuctionGoodsList()));}});});boolean allThreadsIsDone = pool.getTaskCount() == pool.getCompletedTaskCount();while (!allThreadsIsDone) {allThreadsIsDone = pool.getTaskCount() == pool.getCompletedTaskCount();}pool.shutdown();}for (AuctionListByUserIdResponse info : pageResponse.getData()){System.out.println(info.getTransactionPrice() + "," + info.getCostPrice());}return pageResponse;
}

相关文章:

  • Google Earth Engine(GEE)——计算闪闪红星的ndvi的值和直方图(时序分析)
  • 12.1 Go 测试的概念
  • 游戏心理学Day17
  • 区间预测 | Matlab实现EVO-CNN-SVM能量谷算法优化卷积神经网络支持向量机结合核密度估计多置信区间多变量回归区间预测
  • SpringBootWeb 篇-入门了解 Apache POI 使用方法
  • Docker配置代理
  • 【C语言】排序算法 -------- 计数排序
  • 课时158:脚本发布_简单脚本_远程执行
  • 线程相关的基本方法
  • 什么是内存泄漏?如何避免?
  • Android --- 异步操作
  • vscode插件开发之 - 消息通信
  • Apache HttpClient总览
  • QSS/QFrame/connect/两个窗口界面的连接/窗口的优化
  • DoIP——step2:车辆发现
  • hexo+github搭建个人博客
  • 分享的文章《人生如棋》
  • 【MySQL经典案例分析】 Waiting for table metadata lock
  • - C#编程大幅提高OUTLOOK的邮件搜索能力!
  • HTTP中的ETag在移动客户端的应用
  • JAVA 学习IO流
  • Javascript Math对象和Date对象常用方法详解
  • OpenStack安装流程(juno版)- 添加网络服务(neutron)- controller节点
  • React16时代,该用什么姿势写 React ?
  • 对超线程几个不同角度的解释
  • 对象引论
  • 分享几个不错的工具
  • 欢迎参加第二届中国游戏开发者大会
  • 漂亮刷新控件-iOS
  • 使用iElevator.js模拟segmentfault的文章标题导航
  • 微服务核心架构梳理
  • 应用生命周期终极 DevOps 工具包
  • ​学习笔记——动态路由——IS-IS中间系统到中间系统(报文/TLV)​
  • ![CDATA[ ]] 是什么东东
  • # 执行时间 统计mysql_一文说尽 MySQL 优化原理
  • #HarmonyOS:基础语法
  • #if和#ifdef区别
  • (¥1011)-(一千零一拾一元整)输出
  • (12)Linux 常见的三种进程状态
  • (2020)Java后端开发----(面试题和笔试题)
  • (4) openssl rsa/pkey(查看私钥、从私钥中提取公钥、查看公钥)
  • (echarts)echarts使用时重新加载数据之前的数据存留在图上的问题
  • (NO.00004)iOS实现打砖块游戏(十二):伸缩自如,我是如意金箍棒(上)!
  • (Spark3.2.0)Spark SQL 初探: 使用大数据分析2000万KF数据
  • (免费领源码)Java#ssm#MySQL 创意商城03663-计算机毕业设计项目选题推荐
  • (三维重建学习)已有位姿放入colmap和3D Gaussian Splatting训练
  • (图)IntelliTrace Tools 跟踪云端程序
  • (已解决)vue+element-ui实现个人中心,仿照原神
  • (原創) 人會胖會瘦,都是自我要求的結果 (日記)
  • (转)从零实现3D图像引擎:(8)参数化直线与3D平面函数库
  • **PHP二维数组遍历时同时赋值
  • .NET C# 使用 SetWindowsHookEx 监听鼠标或键盘消息以及此方法的坑
  • .NET Core中的时区转换问题
  • .net 前台table如何加一列下拉框_如何用Word编辑参考文献
  • .NET简谈设计模式之(单件模式)