转自:https://blog.csdn.net/qq_26607531/article/details/112343509
作者:壮壮是个智障啊
最近有个业务需求要批量导出大量的数据,但数据库在面对过多数据查询时效率就会很慢,于是考虑使用多个线程来实现。
这里使用了Callable的方式创建多线程,好处是有返回值
package com.next.jiangzh.film.dao;
import java.util.List;
import java.util.concurrent.Callable;
import com.next.jiangzh.film.dao.mapper.NextUserMapper;
public class test implements Callable<List> {
private int start;//当前页数
private int num;//每页查询多少条
private List page;//每次分页查出来的数据
public test(int start,int num,NextUserMapper nextUserMapper) {
this.start=start;
this.num=num;
//分页查询数据库数据
page=nextUserMapper.getUsers(start, num);
}
@Override
public List call() throws Exception {
//返回数据给Future
return page;
}
}
测试方法
这里使用ExecutorService 方法创建线程,因为我的表里数据量较少,因此设置每次查询3条数据。
package com.next.jiangzh.film.dao.mapper;
import com.next.jiangzh.film.controller.cinema.vo.CinemaFilmInfoVO;
import com.next.jiangzh.film.controller.cinema.vo.CinemaFilmVO;
import com.next.jiangzh.film.controller.cinema.vo.FieldHallInfoVO;
import com.next.jiangzh.film.dao.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
@RunWith(SpringRunner.class)
@SpringBootTest
public class FilmFieldTMapperTest2 {
@Autowired
private NextUserMapper nextUserMapper;
@Test
public void describeFieldListTest() throws InterruptedException, ExecutionException{
List<List> result = new ArrayList<>();//返回结果
//查询数据库总数量
int count = nextUserMapper.count();
int num = 3;//一次查询多少条
//需要查询的次数
int times = count / num;
if (count % num != 0) {
times = times + 1;
}
//开始页数 连接的是Mysql的数据库 封装的分页方式 我的是从0开始
int start = 0;
//定义固定长度的线程池 防止线程过多
ExecutorService executorService = Executors.newFixedThreadPool(15);
//Callable用于产生结果
List<Future<List>> futureList = new ArrayList<Future<List>>();
for (int i = 0; i < times; i++) {
Future<List> qfe = executorService.submit(new test(start, num,nextUserMapper));
futureList.add(qfe);
start += num;
}
//处理线程返回结果
if(futureList!=null&&futureList.size()>0){
for (Future<List> future:futureList){
result.addAll(future.get());
}
}
executorService.shutdown();//关闭线程池
}
}