Java 多线程并发 Future+callable 实例
需求:一个业务实现 查询, 因为 要查询十几次, 所以每个平均0.6秒, 之前只有主线程一步步查 ,结果用了10秒,效率十分低下 , 于是改用线程池并发:
以下是代码设计:
1.线程池工具类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | package cn.ycmedia.common.utils; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadPools { private ThreadPools() { } private static final int COUNT = 10 ; private static ExecutorService FIXED_THREAD_POOL = null ; static { if (FIXED_THREAD_POOL == null ) { FIXED_THREAD_POOL = Executors.newFixedThreadPool(COUNT); } } public static ExecutorService getExecutorService() { return FIXED_THREAD_POOL; } } |
2.callableUtil 类
package cn.ycmedia.common.utils; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import com.alibaba.fastjson.JSONObject; import cn.ycmedia.common.constants.PeopleClassEnum; import cn.ycmedia.common.constants.PeopleEnum; import cn.ycmedia.dao.mysql.OverviewDao; import cn.ycmedia.model.ChartBaseBo; import cn.ycmedia.model.overview.PerspectiveBaseBo; /** * 获取返透视数据 * @author 朱良兴 * */ public class CallbleUtil implements Callable<JSONObject> { /** * 透视类型 名称或者分类 */ private String[] name ; /** * 透视种类 项目透视/app 透视 */ private Integer flag; private PeopleEnum methodName; private OverviewDao overviewDao; @Override public JSONObject call() throws Exception { JSONObject json = new JSONObject(); try { switch (methodName) { case FINDGENDERDATA: json.put("genderList", overviewDao.findgenderData(name, flag)); break; case FINDAGEDATA : json.put("ageList", overviewDao.findAgeData(name, flag)); break; case FINDMARRYDATA: json.put("marryList", overviewDao.findMarryData(name, flag)); break; case FINDCONSUMPTIONCAPACITY: json.put("consumptionCapacityList", overviewDao.findConsumptionCapacity(name, flag)); break; case FINDINTERNETACTIVITY: json.put("internetActivityList", overviewDao.findInternetActivity(name, flag)); break; case FINDINTERNETACTIVETIMELIST: json.put("internetActiveTimeList", overviewDao.findInternetActiveTimeList(name, flag)); break; case FINDSHOPPINGPREFERENCELIST: json.put("shoppingPreferenceList", overviewDao.findShoppingPreferenceList(name, flag)); break; case FINDGAMEPREFERENCEDATA: json.put("gamePreferenceList", overviewDao.findGamePreferenceData(name, flag)); break; case FINDAPPLICATIONPREFERENCEDATA: json.put("applicationPreferenceList", overviewDao.findApplicationPreferenceData(name, flag)); break; case FINDMEDIAPREFERENCELIST: json.put("mediaPreferenceList", overviewDao.findMediaPreferenceList(name, flag)); break; case FINDMOBILEBRANDLIST: json.put("mobileBrandList", overviewDao.findMobileBrandList(name, flag)); break; case FINDMOBILESYSTEMLIST: json.put("mobileSystemList", overviewDao.findMobileSystemList(name, flag)); break; case FINDBROSWERLIST: json.put("broswerList", overviewDao.findbroswerList(name, flag)); break; case FINDPHONEMODEL: json.put("phoneModel", overviewDao.findPhoneModel(name, flag)); break; default: break; } } catch (Exception e) { e.printStackTrace(); } return json; } public String[] getName() { return name; } public void setName(String[] name) { this.name = name; } public Integer getFlag() { return flag; } public void setFlag(Integer flag) { this.flag = flag; } public PeopleEnum getMethodName() { return methodName; } public void setMethodName(PeopleEnum methodName) { this.methodName = methodName; } public OverviewDao getOverviewDao() { return overviewDao; } public void setOverviewDao(OverviewDao overviewDao) { this.overviewDao = overviewDao; } public CallbleUtil(String[] name, Integer flag, PeopleEnum methodName, OverviewDao overviewDao) { this.name = name; this.flag = flag; this.methodName = methodName; this.overviewDao = overviewDao; } }
3.枚举类:
package cn.ycmedia.common.constants; /** * @author 透视方法枚举 * */ public enum PeopleEnum { FINDGENDERDATA, FINDAGEDATA, FINDMARRYDATA, FINDCONSUMPTIONCAPACITY, FINDINTERNETACTIVITY, FINDINTERNETACTIVETIMELIST, FINDSHOPPINGPREFERENCELIST, FINDGAMEPREFERENCEDATA, FINDAPPLICATIONPREFERENCEDATA, FINDMEDIAPREFERENCELIST, FINDMOBILEBRANDLIST, FINDMOBILESYSTEMLIST, FINDBROSWERLIST, FINDPHONEMODEL }
4.主线程:
/** * 根据域名获取 * * @param name * @param flag * @param second * @param first * @return * @throws ExecutionException * @throws InterruptedException */ public List<JSONObject> getPeoplePerspective(String name, Integer flag,Integer type) throws InterruptedException, ExecutionException { String[] nameArr = name.split(","); ExecutorService pool=ThreadPools.getExecutorService(); List<Future<JSONObject>>results=new ArrayList<Future<JSONObject>>(); List<JSONObject> list= new ArrayList<JSONObject>(); if(type==1){ for (PeopleEnum enums:PeopleEnum.values()) { results.add(pool.submit(new CallbleUtil(name.split(",") ,flag, enums, overviewDao))); } }else{ for (PeopleClassEnum enums:PeopleClassEnum.values()) { results.add(pool.submit(new CallbelClassUtil(Integer.parseInt(name) ,flag, enums, overviewDao))); } } for(Future<JSONObject> fs :results) { list.add(fs.get()); } String audienceStr=""; String flow=""; // 受众 Long audience = 0L; if(type==1){ audience=overviewDao.getFlow(nameArr, flag); }else{ audience = overviewDao.getFlowClass(Integer.parseInt(name), flag); } if (audience != null) { audienceStr=audience.toString(); flow=String.valueOf(overviewDao.findLiuLiang(audience)); } else { audienceStr="--"; flow="--"; } JSONObject audienceJ = new JSONObject(); audienceJ.put("audience", audienceStr); JSONObject flowJ= new JSONObject(); flowJ.put("flow",flow ); list.add(flowJ); list.add(audienceJ); return list; }
======================================================================
测试:
==================================1.8 秒还是可以接受的
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux glibc自带哈希表的用例及性能测试
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 现代计算机视觉入门之:什么是图片特征编码
· 手把手教你在本地部署DeepSeek R1,搭建web-ui ,建议收藏!
· Spring AI + Ollama 实现 deepseek-r1 的API服务和调用
· 数据库服务器 SQL Server 版本升级公告
· 程序员常用高效实用工具推荐,办公效率提升利器!
· C#/.NET/.NET Core技术前沿周刊 | 第 23 期(2025年1.20-1.26)