多线程处理多表同时查询
知识点
通过ThreadPoolExecutor创建多线程
场景
场景说明:一个业务流程需要去查询数据库四次(分别是查询不同的表)
业务处理时间:(
4O
)
使用多线程处理
处理说明:通过创建线程池,分别查询单表中的数据。然后通过Futrue来汇总查询结果。从而降低业务处理时间
业务处理时间:(
O
)
源代码
public String test() {
//核心线程数
int corePoolSize = 2;
//最大线程数
int maximumPoolSize = 2;
//超过 corePoolSize 线程数量的线程最大空闲时间
long keepAliveTime = 2;
//以秒为时间单位
TimeUnit unit = TimeUnit.SECONDS;
//创建工作队列,用于存放提交的等待执行任务
BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(2);
ThreadPoolExecutor threadPoolExecutor = null;
List<Future<Object>> futureTaskList = new ArrayList<>(2);
//创建线程池
try {
threadPoolExecutor = new ThreadPoolExecutor(corePoolSize,
maximumPoolSize,
keepAliveTime,
unit,
workQueue,
new ThreadPoolExecutor.AbortPolicy());
// 执行查询user
futureTaskList.add(
threadPoolExecutor.submit(() -> userService.findAllUser()
));
// 执行查询Student
futureTaskList.add(
threadPoolExecutor.submit(() -> studentService.findAllStudent()
));
} finally {
assert threadPoolExecutor != null;
// 关闭线程池
threadPoolExecutor.shutdown();
}
// 处理返回参数
List<UserVO> userVOS = new ArrayList<>();
List<StudentVO> studentPOS = new ArrayList<>();
try {
userVOS = (List<UserVO>) futureTaskList.get(0).get();
studentPOS = (List<StudentVO>) futureTaskList.get(1).get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
System.err.println("用户信息:" + userVOS);
System.err.println("学生信息:" + studentPOS);
return "业务完成!";
}