Spring @Async开启异步任务

定义线程池
 @Configuration
 @EnableAsync
 public class TaskPoolConfig {

        @Bean("taskExecutor")
        public Executor taskExecutro(){
            ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
            taskExecutor.setCorePoolSize(5);//初始化5个线程
            taskExecutor.setMaxPoolSize(5);//最大线程数5个
            taskExecutor.setQueueCapacity(500);//缓冲队列
//允许线程空闲时间,当超过了核心线程出之外的线程在空闲时间到达之后会被销毁
            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");
        }
}

你可能感兴趣的:(Spring @Async开启异步任务)