newFixedThreadPool,固定线程池
newSingleThreadExecutor,一个线程池
newCachedThreadPool 无线线程池
/** * 线程池配置 * * @author Miguel.hou * @version v1.0 * @date 2019-03-28 */ @Configuration public class ThreadPoolConfig { @Resource private TradeProperty tradeProperty; /** * 日志收集线程池 * @return */ @Bean public ThreadPoolTaskExecutor logCollectExecutor() { ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); // 核心池大小 taskExecutor.setCorePoolSize(10); // 最大池大小 taskExecutor.setMaxPoolSize(20); // 线程池等待队列最大长度 taskExecutor.setQueueCapacity(500); taskExecutor.setThreadNamePrefix("THREAD-POOL"); // 等待队列满后策略 taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy()); return taskExecutor; } }
/** * 阻塞的异步线程池配置 */ @EnableAsync @Configuration @Slf4j public class BlockingAsyncConfiguration { /** * 线程池工作的线程总数 * Set the ThreadPoolExecutor's core pool size. */ private int corePoolSize = 5; /** * 线程池工作极限的告警数量值,如果达到极限值并且工作队列已满,将按照策略执行 * Set the ThreadPoolExecutor's maximum pool size. */ private int maxPoolSize = 15; /** * 持有等待执行的任务队列. * Set the capacity for the ThreadPoolExecutor's BlockingQueue. */ private int queueCapacity = 200; private static final String threadNamePrefix_data = "blocking-async-executor-"; @Bean public Executor blockingAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(corePoolSize); executor.setMaxPoolSize(maxPoolSize); executor.setQueueCapacity(queueCapacity); executor.setThreadNamePrefix(threadNamePrefix_data); executor.setKeepAliveSeconds(0); executor.setRejectedExecutionHandler((Runnable r, ThreadPoolExecutor threadPoolExecutor) -> { if (!threadPoolExecutor.isShutdown()) { try { // 基于BlockingQueue的put方法来实现,当阻塞队列满时,put方法会一直等待 threadPoolExecutor.getQueue().put(r); } catch (InterruptedException e) { log.error(e.toString(), e); Thread.currentThread().interrupt(); } } } ); executor.initialize(); return executor; } }