SpringBoot全局线程池
前言
在处理导入导出exel的时候,如果数据比较多需要开启线程池来加快处理速度。单独设置线程池很耗费时间,而且代码丑陋,我们可以通过公共线程池来解决这一问题。
正文:
线程池配置类:ThreadToolConfig.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
@EnableAsync
@Slf4j
public class ThreadToolConfig {
@Bean("threadPool")
public Executor msgThreadPool() {
//获取当前机器的核数
int cpuNum = Runtime.getRuntime().availableProcessors();
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//配置核心线程数cpuNum
executor.setCorePoolSize(cpuNum);
//配置最大线程数cpuNum * 2
executor.setMaxPoolSize(cpuNum * 2);
//配置队列大小
executor.setQueueCapacity(300);
//线程存活时间
executor.setKeepAliveSeconds(60);
//配置线程池中的线程的名称前缀
executor.setThreadNamePrefix("pool-thread-");
// CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
log.error("线程池初始化--->核心线程数:{},最大线程数:{},队列大小:{}",cpuNum,cpuNum * 2,300);
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//执行初始化
executor.initialize();
return executor;
}
}
需要多线程调用方法对应的工具类:MutiThreadUtil.java
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@SneakyThrows
@Async("threadPool")
public void sendMessageText(String msg, List<String> list){
log.error("线程名:" + Thread.currentThread().getName());
log.error("发送消息时间{},编号{}:",System.currentTimeMillis(),msg);
list.add(msg);
}
调用
@Autowired
private MutiThreadUtil mutiThreadUtil;
@SneakyThrows
@GetMapping("/send")
public void sendMessageText() {
//两种线程安全的list
List<String> list0 = Collections.synchronizedList(new ArrayList<>());
List<String> list = new CopyOnWriteArrayList<>();
for (int i = 0; i < 100; i++) {
mutiThreadUtil.sendMessageText(i + "",list);
}
Thread.sleep(1000);
System.out.println("消息条数"+ list.size());
}