1、线程池配置:
@Configuration
@EnableAsync
public class ExecutorConfig {
@Bean("taskExecutor")
public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setCorePoolSize(10);
threadPoolTaskExecutor.setMaxPoolSize(10);
threadPoolTaskExecutor.setQueueCapacity(20);
threadPoolTaskExecutor.setKeepAliveSeconds(3000);
threadPoolTaskExecutor.setThreadNamePrefix("Async-Service-");
threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return threadPoolTaskExecutor;
}
}
@EnableAsync 注解是在springBoot中开启Async
2、模拟数据库查询出的list操作,调用多线程处理类,注意@Async注解的处理类不能和调用一个类
@Component
public class QueryDataExec {
@Autowired
private TaskDataExec taskDataExec;
public void execData() {
ArrayList<String> list = new ArrayList<>();
for(int i=0; i<10; i++) {
taskDataExec.taskDataExec("id-"+i);
}
}
}
3、@Async 处理类
@Component
public class TaskDataExec {
Logger log = LoggerFactory.getLogger(TaskDataExec.class);
@Async("taskExecutor")
public void taskDataExec(String id) {
log.info("开始处理:" + id);
log.info("完成处理:" + id);
}
}
4、测试用例
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestDataExec {
@Autowired
private QueryDataExec queryDataExec;
@Test
public void dataExecTest() {
queryDataExec.execData();
}
}
5、结果显示