轉載自:https://blog.csdn.net/qq_30281443/article/details/83340909
線程是開發中常用到的,但是如果沒有定義線程池,程序不斷的創建,銷毀線程,需要消耗很多時間,所以我們定義線程池可以減小這部分時間,我來實現AsyncConfigurer來配置線程池,先看看這個接口有什么方法
public interface AsyncConfigurer { Executor getAsyncExecutor(); AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler(); }
Executor : 處理異步方法調用時要使用的實例,
AsyncUncaughtExceptionHandler :在使用void返回類型的異步方法執行期間拋出異常時要使用的實例。
實現接口代碼如下:
@Configuration @EnableAsync @EnableScheduling public class AsyncConfiguration implements AsyncConfigurer { private final Logger log = LoggerFactory.getLogger(AsyncConfiguration.class); @Override @Bean(name = "taskExecutor") public Executor getAsyncExecutor() { log.debug("Creating Async Task Executor"); ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(10); //核心線程數 executor.setMaxPoolSize(20); //最大線程數 executor.setQueueCapacity(1000); //隊列大小 executor.setKeepAliveSeconds(300); //線程最大空閑時間 executor.setThreadNamePrefix("ics-Executor-"); ////指定用於新創建的線程名稱的前綴。 executor.setRejectedExecutionHandler( new ThreadPoolExecutor.CallerRunsPolicy()); // 拒絕策略 return new ExceptionHandlingAsyncTaskExecutor(executor); } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return new SimpleAsyncUncaughtExceptionHandler(); } }
其中我們主要注意的就是拒絕策略方法:setRejectedExecutionHandler(),拒絕策略常用有有這四種
ThreadPoolExecutor.AbortPolicy 丟棄任務並拋出RejectedExecutionException異常(默認)。
ThreadPoolExecutor.DiscardPolic 丟棄任務,但是不拋出異常。
ThreadPoolExecutor.DiscardOldestPolicy 丟棄隊列最前面的任務,然后重新嘗試執行任務
ThreadPoolExecutor.CallerRunsPolic 由調用線程處理該任務
還有一篇博文寫的很好,https://www.cnblogs.com/memoryXudy/p/7737190.html
