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!");
    });
}

实付 9.90元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值