線程池ExecutorService的4種拒絕策略
-
ThreadPoolExecutor.AbortPolicy
:丟棄任務并拋出RejectedExecutionException異常 -
ThreadPoolExecutor.DiscardPolicy
:也是丟棄任務,但是不拋出異常。 -
ThreadPoolExecutor.DiscardOldestPolicy
:丟棄隊列最前面的任務,執(zhí)行后面的任務 -
ThreadPoolExecutor.CallerRunsPolicy
:由調用線程處理該任務
原生線程池實現(xiàn)
// Spring原生線程池
ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
.setNameFormat("demo-pool-%d").build();
ExecutorService singleThreadPool = new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
singleThreadPool.execute(() -> System.out.println(Thread.currentThread().getName()));
singleThreadPool.shutdown();
SpringMVC集成
xml聲明
<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<!-- 線程池維護線程的最少數(shù)量 -->
<property name="corePoolSize" value="2" />
<!-- 線程池維護線程的最大數(shù)量 -->
<property name="maxPoolSize" value="1000" />
<!-- 線程池所使用的緩沖隊列 -->
<property name="queueCapacity" value="200" />
<!-- 線程池維護線程所允許的空閑時間 -->
<property name="keepAliveSeconds" value="2000" />
<property name="rejectedExecutionHandler">
<bean class="java.util.concurrent.ThreadPoolExecutor$AbortPolicy" />
</property>
</bean>
SpringBoot集成
/**
* 放一些自定義的Bean聲明
*
* @author Created by 思偉 on 2019/12/16
*/
@Configuration
@EnableAsync
public class MyBootConfig {
/**
* 線程池維護線程的最少數(shù)量
*/
@Value("${thread-pool.core-pool-size:2}")
private int corePoolSize;
/**
* 線程池維護線程的最大數(shù)量
*/
@Value("${thread-pool.max-pool-size:1000}")
private int maxPoolSize;
/**
* 線程池所使用的緩沖隊列
*/
@Value("${thread-pool.queue-capacity:200}")
private int queueCapacity;
/**
* 線程池維護線程所允許的空閑時間
*/
@Value("${thread-pool.keep-alive-seconds:2000}")
private int keepAliveSeconds;
/**
* 配置線程池中的線程的名稱前綴
*/
@Value("${thread-pool.thread-name-prefix:async-resource-schedule-}")
private String threadNamePrefix;
/**
* Spring線程池
*
* @return TaskExecutor
*/
@Bean(name = AsyncExecutionAspectSupport.DEFAULT_TASK_EXECUTOR_BEAN_NAME)
@ConditionalOnMissingBean
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setKeepAliveSeconds(keepAliveSeconds);
executor.setThreadNamePrefix(threadNamePrefix);
// rejection-policy:當pool已經(jīng)達到max size的時候,如何處理新任務
// CALLER_RUNS:不在新線程中執(zhí)行任務,而是有調用者所在的線程來執(zhí)行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
//執(zhí)行初始化
executor.initialize();
return executor;
}
}
如何使用
/**
* Spring線程池
*/
@Resource
private TaskExecutor taskExecutor;
@Override
public void run(String... args) throws Exception {
taskExecutor.execute(() -> {
log.info("Real thread begin to execute!");
});
}