前言
在开发时不可避免会遇到多线程的问题,在此提供多线程模板,以便于快速开发。
线程池属性
通过配置文件设置线程池的属性
mythreadpool:
maxPoolSize: 20
corePoolSize: 4
queueCapacity: 2048
keepAliveSeconds: 60
threadNamePrefix: springThreadPool-
waitForTasksToCompleteOnShutdown: true
自定义线程配置类
/**
* @Description: 自定义线程池
* @Author: Junior
* @Date: 2022/5/28
*/
@Configuration
@EnableAsync
public class MyThreadPool {
@Value("${mythreadpool.maxPoolSize}")
private Integer maxPoolSize;
@Value("${mythreadpool.corePoolSize}")
private Integer corePoolSize;
@Value("${mythreadpool.queueCapacity}")
private Integer queueCapacity;
@Value("${mythreadpool.keepAliveSeconds}")
private Integer keepAliveSeconds;
@Value("${mythreadpool.threadNamePrefix}")
private String threadNamePrefix;
@Value("${mythreadpool.waitForTasksToCompleteOnShutdown}")
private Boolean waitForTasksToCompleteOnShutdown;
@Bean("taskExecutor") //注册为Bean,方便使用
public Executor asyncServiceExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 设置核心线程数等于系统核数--8核
// int availableProcessors = Runtime.getRuntime().availableProcessors();
executor.setCorePoolSize(corePoolSize);
// 设置最大线程数
executor.setMaxPoolSize(maxPoolSize);
//配置队列大小
executor.setQueueCapacity(queueCapacity);
// 设置线程活跃时间(秒)
executor.setKeepAliveSeconds(keepAliveSeconds);
// 线程满了之后由调用者所在的线程来执行
// 拒绝策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
// 设置默认线程名称
executor.setThreadNamePrefix(threadNamePrefix);
// 等待所有任务结束后再关闭线程池
executor.setWaitForTasksToCompleteOnShutdown(waitForTasksToCompleteOnShutdown);
//执行初始化
executor.initialize();
return executor;
}
}
简单使用
只需要在需要并发执行的方法上面加上
@Async("taskExecutor")
注解
@Async("taskExecutor")
@Override
public CompletableFuture<Long> doMethod(String message) {
Long j = 0L;
for (long i = 0L; i < 1000L; i++) {
j++;
}
System.out.println(Thread.currentThread().getName() + "执行了"+ j.toString());
return CompletableFuture.completedFuture(j);
}
评论区