天天看点

java多线程查询_java使用多线程及分页查询数据量很大的数据

调用方法: 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> getMaxResult(String sex) throws Exception{ long start = System.currentTimeMillis(); List> result=new ArrayList<>();//返回结果 int count = 20000005;//mydao.getCount(); 通过count查到数据总量 int num = 10000;//每次查询的条数 //需要查询的次数 int times=count / num; if(count!=0) { times=times+1; } //开始查询的行数 int bindex = 0; List>>> tasks = new ArrayList>>>();//添加任务 for(int i = 0; i >> qfe = new ThredQuery(myService,sex,bindex, num); tasks.add(qfe); bindex=bindex+num; } //定义固定长度的线程池 防止线程过多 ExecutorService execservice = Executors.newFixedThreadPool(15); List>>> futures = execservice.invokeAll(tasks); // 处理线程返回结果 if (futures != null && futures.size() > 0) { for(Future>> 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>> { private Object myService;//需要通过够早方法把对应的业务service传进来 实际用的时候把类型变为对应的类型 private String sex;//查询条件 根据条件来定义该类的属性 private int bindex;//分页index private int 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> call() throws Exception { //通过service查询得到对应结果 List> list =new ArrayList<>(); //myService.queryBySex(sex,bindex,num); return list; } }