springboot配置线程池
直接上代码
配置
定义一个配置类
创建一个springboot能扫描到的地方创建一个线程池配置类
配置信息
package com.example.demonew.config;
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;
@Configuration //表明是配置类,springboot会来扫描
public class ThreadPoolConfig {
@Bean(name="taskExecutor") //配置bean对象交给springboot容器给我们管理,这时候就相当于创建了一个单例线程池名字为taskExecutor
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(100);
executor.initialize();
return executor;
}
@Bean("poolExecutor") //配置第二个线程池
public Executor poolExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
//设置线程池参数信息
taskExecutor.setCorePoolSize(10);
taskExecutor.setMaxPoolSize(50);
taskExecutor.setQueueCapacity(200);
taskExecutor.setKeepAliveSeconds(60);
taskExecutor.setThreadNamePrefix("myExecutor2--");
taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
taskExecutor.setAwaitTerminationSeconds(60);
//修改拒绝策略为使用当前线程执行
taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//初始化线程池
taskExecutor.initialize();
return taskExecutor;
}
}
实现
package com.example.demonew.service;
import com.example.demonew.config.ThreadPoolConfig;
import jakarta.annotation.Resource;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import java.util.concurrent.Executors;
@Service
public class TestServiceImpl implements TestService{
@Resource(name = "taskExecutor") //指定注入的bean 可以切换成poolExecutor
private ThreadPoolTaskExecutor executor;
@Override
public String test() {
ThreadPoolTaskExecutor taskExecutor = executor;
// 获取线程池信息
int activeCount = taskExecutor.getActiveCount();
int corePoolSize = taskExecutor.getCorePoolSize();
int poolSize = taskExecutor.getPoolSize();
taskExecutor.execute(()->{
System.out.printf(activeCount+"--"+corePoolSize);
});
return null;
}
}
结果
@Resource(name = "taskExecutor") //指定注入的bean 可以切换成poolExecutor
private ThreadPoolTaskExecutor executor;
@Resource(name = "poolExecutor")
private ThreadPoolTaskExecutor executor;
切换成功