jdk8有一个异步类CompletableFuture可以使用线程池帮助我们实现多线程查询
@PostConstruct
private void multithreadingGetData() {
// 数据总量
int count = 312;
// 计算机可用cpu 设置线程池个数最好与之匹配
int availableProcessors = Runtime.getRuntime().availableProcessors();
// 每个线程要查多少条
int num = count / availableProcessors;
ExecutorService executorService = Executors.newFixedThreadPool(availableProcessors);
List<CompletableFuture> futures = new ArrayList<>();
long start = System.currentTimeMillis();
for (int i = 0; i < num; i++) {
int id = (i + 1) * num;
if(id <= count){
//futures.add(CompletableFuture.supplyAsync(() -> officeResponsibilityMapper.multithreadingGetData(id), executorService));
CompletableFuture.supplyAsync(() -> officeResponsibilityMapper.multithreadingGetData(id), executorService);
}
}
executorService.shutdown();
System.out.println("多线程查询共用时间" + (System.currentTimeMillis() - start));
long start2 = System.currentTimeMillis();
officeResponsibilityMapper.selectAll();
System.out.println("单线程查询共用时间" + (System.currentTimeMillis() - start2));
// List<Object> collect = futures.stream().map(CompletableFuture::join).collect(Collectors.toList());
}
public interface OfficeResponsibilityMapper extends Mapper<OfficeResponsibilityEntity> {
@Select("select * from office_responsibility where id <= #{id}" )
List<OfficeResponsibilityEntity> multithreadingGetData(@Param("id") Integer id);
}
输出如下
这还是仅有300条数据,数据多了之后使用多线程查效率高的可不是一点点