定義線程池
@Configuration
@EnableAsync
public class TaskPoolConfig {
@Bean("taskExecutor")
public Executor taskExecutro(){
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(5);//初始化5個(gè)線程
taskExecutor.setMaxPoolSize(5);//最大線程數(shù)5個(gè)
taskExecutor.setQueueCapacity(500);//緩沖隊(duì)列
//允許線程空閑時(shí)間屈溉,當(dāng)超過了核心線程出之外的線程在空閑時(shí)間到達(dá)之后會(huì)被銷毀
taskExecutor.setKeepAliveSeconds(60);
taskExecutor.setThreadNamePrefix("--taskTest--");//線程池名的前綴
// taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
taskExecutor.setAwaitTerminationSeconds(60);
return taskExecutor;
}
}
使用線程池
@Slf4j
@Component
public class Task {
@Async("taskExecutor")
public void doTask() throws Exception {
log.info("----start executor------");
long start = System.currentTimeMillis();
long end = System.currentTimeMillis();
log.info("start executor---use:" + (end - start) + "ms");
}
}