网上创建线程池的办法一搜一大堆,现在我把我使用的做一个总结记录
首先是线程池中的各项参数
我只用到了其中几项,在application.yml配置文件
threadpool:
# 核心线程池数(根据自身电脑cpu核数*2+1)(但是考虑通用性,以及使用时的感受在此设置5)
corePoolSize: 5
#最大线程
maxPoolSize: 10
#队列容量(满了的时候,排队的长度)
queueCapacity: 1000
如下是项目所引入的完整代码
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
@EnableAsync
@ConfigurationProperties(prefix = "threadpool")
@PropertySource(name = "application.yml", value = {"classpath:/application.yml"})
public class ExecutorConfig {
@Value("${corePoolSize}")
private int corePoolSize;
@Value("${maxPoolSize}")
private int maxPoolSize;
@Value("${queueCapacity}")
private int queueCapacity;
@Bean(name = "taskExecutor")
public Executor asynsServiceExecutor(){
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setCorePoolSize(corePoolSize);
threadPoolTaskExecutor.setMaxPoolSize(maxPoolSize);
threadPoolTaskExecutor.setQueueCapacity(queueCapacity);
threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
threadPoolTaskExecutor.initialize();
return threadPoolTaskExecutor;
}
}
如果当你的配置文件可以自动搜索到上述配置文件的内容,可以把注释中的下面代码去掉
@PropertySource(name = "application.yml", value = {"classpath:/application.yml"})
一般线程代码都是从controller层使用,下面是引入的代码,service层不动
@Resource(name = "taskExecutor")
private Executor taskExecutor;
//控制层接入service层的入口
taskExecutor.execute(()->{
try {
//service方法
} catch (InterruptedException e) {
e.printStackTrace();
}
});