业务背景:
有一批5~10W的Excel文件,使用Poi直接拿到了一个大的List集合,在进行业务遍历时,发现速度堪忧,5W数据大概要跑1个小时。决定使用多线程对其进行优化
第一步.声明一个线程池对象
此处直接定义一个线程池交由spring进行管理
@EnableAsync @Component public class AsyncThreadPool {
@Bean("ThreadPoolTaskExecutor")
public ThreadPoolTaskExecutor initializeThreadPool() {
ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor ();
threadPool.setCorePoolSize(5);
threadPool.setMaxPoolSize(10);
threadPool.setQueueCapacity(1000);
threadPool.setKeepAliveSeconds(30);
threadPool.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
threadPool.initialize();
return threadPool;
}
}
第二步,新建类,里面写具体业务逻辑代码,开启异步且指定线程池对象
@Slf4j
@Async("ThreadPoolTaskExecutor")
@Component public class AsyncThreadUpdate {
public Future 方法名(参数~可有可不有){
这里写具体业务逻辑
return new AsyncResult(true);
}
}
第三步,在业务层分批处理数据并调用此异步方法
List> futures = new ArrayList >(strList.size()/ThreadPool_NUM); List sonList = strList.subList(i, i + toIndex); Future future = asyncThreadUpdate.getThreadFuture(参数~可以不加); futures.add(future) for (Future future : futures) { future.get(); }
备注:
上面方法执行完毕后发现并不理想,是因为没有调用线程等待,即:等待所有的task任务结束后才继续往下执行



