主要的思路就是:
先通过count查出结果集的总条数,设置每个线程分页查询的条数,通过总条数和单次条数得到线程数量,通过改变limit的下标实现分批查询。
调用方法:
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class QueryTest {
@Autowired
Object myService;
public List<Map<String, Object>> getMaxResult(String sex) throws Exception{
long start = System.currentTimeMillis();
List<Map<String, Object>> result=new ArrayList<>();//返回结果
int count = 20000005;//mydao.getCount(); 通过count查到数据总量
int num = 10000;//每次查询的条数
//需要查询的次数
int times=count / num;
if(count%num !=0) {
times=times+1;
}
//开始查询的行数
int bindex = 0;
List<Callable<List<Map<String, Object>>>> tasks = new ArrayList<Callable<List<Map<String, Object>>>>();//添加任务
for(int i = 0; i <times ; i++){
Callable<List<Map<String, Object>>> qfe = new ThredQuery(myService,sex,bindex, num);
tasks.add(qfe);
bindex+=bindex;
}
//定义固定长度的线程池 防止线程过多
ExecutorService execservice = Executors.newFixedThreadPool(15);
List<Future<List<Map<String, Object>>>> futures = execservice.invokeAll(tasks);
// 处理线程返回结果
if (futures != null && futures.size() > 0) {
for(Future<List<Map<String, Object>>> future : futures) {
result.addAll(future.get());
}
}
execservice.shutdown(); // 关闭线程池
long end = System.currentTimeMillis();
System.out.println("用时"+(start-end));
return result;
}
}
线程类:
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
public class ThredQuery implements Callable<List<Map<String, Object>>> {
private Object myService;//需要通过够早方法把对应的业务service传进来 实际用的时候把类型变为对应的类型
private String sex;//查询条件 根据条件来定义该类的属性
private int bindex;//分页index
private int num;//数量
/**
* 重新构造方法
* @param myService
* @param sex
* @param bindex
* @param num
*/
public ThredQuery(Object myService,String sex,int bindex,int num){
this.myService=myService;
this.sex=sex;
this.bindex=bindex;
this.num=num;
}
@Override
public List<Map<String, Object>> call() throws Exception {
//通过service查询得到对应结果
List<Map<String, Object>> list =new ArrayList<>(); //myService.queryBySex(sex,bindex,num);
return list;
}
}