1.配置類
package cn.com.bonc.util; import java.util.concurrent.Executor; import java.util.concurrent.ThreadPoolExecutor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; @Configuration @EnableAsync public class MyThread { private int corePoolSize = 10;//線程池維護線程的最少數量 private int maxPoolSize = 30;//線程池維護線程的最大數量 private int queueCapacity = 8; //緩存隊列 private int keepAlive = 60;//允許的空閑時間 @Bean public Executor myExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(corePoolSize); executor.setMaxPoolSize(maxPoolSize); executor.setQueueCapacity(queueCapacity); executor.setThreadNamePrefix("mqExecutor-");
// rejection-policy:當pool已經達到max size的時候,如何處理新任務
// CALLER_RUNS:不在新線程中執行任務,而是由調用者所在的線程來執行 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); //對拒絕task的處理策略 executor.setKeepAliveSeconds(keepAlive); executor.initialize(); return executor; } }
2.注解使用
@Async("myExecutor") //配置類中的方法名
3.啟動類添加
@EnableAsync
