SpringBoot配置ThreadPoolTaskExecutor
ThreadPool
A simple C++11 Thread Pool implementation
项目地址:https://gitcode.com/gh_mirrors/th/ThreadPool
·
package com.example.demo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 1. 当一个任务被提交到线程池时,首先查看线程池的核心线程是否都在执行任务,否就选择一条线程执行任务,是就执行第二步。
* 2. 查看核心线程池是否已满,不满就创建一条线程执行任务,否则执行第三步。
* 3. 查看任务队列是否已满,不满就将任务存储在任务队列中(SynchronousQueue同步队直接执行第四步),否则执行第四步。
* 4. 查看线程池是否已满,不满就创建一条线程执行任务,否则就按照策略处理无法执行的任务。
*/
@Configuration
public class ThreadPoolTaskConfig {
@Bean
public Executor executor(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//此方法返回可用处理器的虚拟机的最大数量; 不小于1
int core = Runtime.getRuntime().availableProcessors();
executor.setCorePoolSize(core);//设置核心线程数
executor.setMaxPoolSize(core*2 + 1);//设置最大线程数
executor.setKeepAliveSeconds(3);//除核心线程外的线程存活时间
executor.setQueueCapacity(40);//如果传入值大于0,底层队列使用的是LinkedBlockingQueue,否则默认使用SynchronousQueue
executor.setThreadNamePrefix("thread-execute");//线程名称前缀
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());//设置拒绝策略
return executor;
}
}
如上述代码已经配置好ThreadPoolTaskExecutor,在spring容器启动的时候会被初始化成bean存放在上下文中。需要使用的话只需要@autowired注入即可。
ThreadPoolTaskExecutor底层调用的就是ThreadPoolExecuter,关于Lee老爷子的线程池原理可以参考之前的一篇博文
https://blog.csdn.net/weixin_43142697/article/details/82875437
A simple C++11 Thread Pool implementation
最近提交(Master分支:4 个月前 )
9a42ec13 - 11 年前
fcc91415 - 11 年前
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐


所有评论(0)