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

多线程优化接口效率

可以用多线程优化的大概有两种情况:

1、存在循环很耗时

2、存在不必要同步处理的耗时代码块(没有但是可以分析拆解出来的)

代码如下

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

 多线程处理后需要数据返回

public List execute(List taskList){//比如taskList有20个任务数据需要处理ExecutorService executorService = Executors.newFixedThreadPool(10);// 提交多个任务Future<?>[] futures = new Future[taskList.size()];for (int i = 0; i < taskList.size(); i++) {final int taskId = i;futures[i] = executorService.submit(() -> {Object dm =taskList.get(taskId);/**执行任务开始**//**执行任务结束**/resultList.add("存放结果");});}// 关闭线程池executorService.shutdown();// 等待所有任务完成List resultList=new ArrayList(20);for (Future<?> future : futures) {try {resultList.add(future.get()); // 阻塞直到任务完成} catch (InterruptedException | ExecutionException e) {e.printStackTrace();}}return resultList;}

不需要数据返回

public void execute(List taskList){//比如taskList有20个任务数据需要处理ExecutorService executorService = Executors.newFixedThreadPool(10);// 提交多个任务Future<?>[] futures = new Future[taskList.size()];for (int i = 0; i < taskList.size(); i++) {final int taskId = i;futures[i] = executorService.submit(() -> {Object dm =taskList.get(taskId);/**执行任务开始**//**执行任务结束**/resultList.add("存放结果");});}// 关闭线程池executorService.shutdown();// 等待所有任务完成for (Future<?> future : futures) {try {future.get(); // 阻塞直到任务完成} catch (InterruptedException | ExecutionException e) {e.printStackTrace();}}}

分析每次处理的数据相似度,次数增大后重复率变高,可以加缓存进一步提高效率

根据数据结果的大小选择本地或者redis,

本地缓存参考,使用方式自行百度

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;


http://www.mrgr.cn/news/13561.html

相关文章:

  • 【生活英语】1、高兴与难过
  • 三级_网络技术_52_应用题
  • 【Spring Boot 3】【Web】自定义过滤器
  • MySQL常用语句
  • Java-异常处理try catch finally throw和throws
  • 【Windows】被遗忘的宝藏:Windows 10 LTSC 2021 官方精简版
  • windows 核心编程DLL 高级技术-延迟载入dll,02
  • scrapy学习笔记0828-下
  • configure.ac和Makefile.am的格式解析概述
  • 【TPAMI 2024】Occlusion-Aware Self-Supervised Monocular 6D Object Pose Estimation
  • ES 根据条件删除文档
  • ARM 寻址方式(18)
  • 《黑神话:悟空》:文化与科技的完美融合
  • 阿里云服务器 篇七:服务器热备份/定时备份
  • Python简介、发展史
  • 前端引入字体文件
  • 秋招突击——知识复习——HTTP/2、HTTP/3的改良
  • 《Cloud Native Data Center Networking》(云原生数据中心网络设计)读书笔记 -- 08网络自动化
  • C#实现利用数据驱动设计与组件系统优化游戏架构示例
  • 牛客周赛 Round 35 (A~G)