天天看點

Spring內建線程池

線程池ExecutorService的4種拒絕政策

  1. ​ThreadPoolExecutor.AbortPolicy​

    ​:丢棄任務并抛出RejectedExecutionException異常
  2. ​ThreadPoolExecutor.DiscardPolicy​

    ​:也是丢棄任務,但是不抛出異常。
  3. ​ThreadPoolExecutor.DiscardOldestPolicy​

    ​:丢棄隊列最前面的任務,執行後面的任務
  4. ​ThreadPoolExecutor.CallerRunsPolicy​

    ​:由調用線程處理該任務

原生線程池實作

// 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">
    <!-- 線程池維護線程的最少數量 -->
    <property name="corePoolSize" value="2" />
    <!-- 線程池維護線程的最大數量 -->
    <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 {

    /**
     * 線程池維護線程的最少數量
     */
    @Value("${thread-pool.core-pool-size:2}")
    private int corePoolSize;

    /**
     * 線程池維護線程的最大數量
     */
    @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已經達到max size的時候,如何處理新任務
        // CALLER_RUNS:不在新線程中執行任務,而是有調用者所在的線程來執行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        //執行初始化
        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!");
    });
}