springboot 中如何配置线程池,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
1.添加config
import lombok.extern.slf4j.Slf4j;
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 ExecutorConfig {
@Bean("taskExecutor")
public Executor asyncServiceExecutor() {
log.info("---创建线程池---");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//核心线程数
executor.setCorePoolSize(10);
//最大线程数
executor.setMaxPoolSize(20);
//队列大小
executor.setQueueCapacity(200);
//配置线程池中的线程的名称前缀
executor.setThreadNamePrefix("async-method-");
/*
rejection-policy:当pool已经达到max size的时候,如何处理新任务
线程池对拒绝任务的处理策略:此处采用了CallerRunsPolicy策略,
当线程池没有处理能力的时候,该策略会直接在execute方法的调用线程中运行被拒绝的任务;
如果执行程序已被关闭,则会丢弃该任务
*/
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//设置线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean
executor.setWaitForTasksToCompleteOnShutdown(true);
//设置线程池中任务的等待时间,如果超过这个时候还没有销毁就强制销毁,以确保应用最后能够被关闭,而不是阻塞住
executor.setAwaitTerminationSeconds(60);
//执行初始化
executor.initialize();
return executor;
}
}
2.定义异步方法
/**
* 异步调用测试接口
*/
public interface IAsyncService {
void testAsyncMethod() throws Exception;
}
@Service
@Slf4j
public class AsyncServiceImpl implements IAsyncService {
//此处taskExecutor和 config中@bean保持一致
@Async("taskExecutor")
@Override
public void testAsyncMethod() throws Exception{
log.info("异步方法,走起---");
long start = System.currentTimeMillis();
Thread.sleep(5000);
long end = System.currentTimeMillis();
log.info("异步方法,结束:" + (end - start) + "毫秒");
}
}
3.测试
public Result<?> test() {
System.out.println("1=====================");
System.out.println("2=====================");
try {
asyncService.testAsyncMethod();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("3=====================");
System.out.println("4=====================");
return Result.ok("测试成功!");
}
控制台打印如下:

备注:
如果发现启动项目报错:

解决方案:yml中添加配置
spring:
main:
allow-bean-definition-overriding: true
看完上述内容,你们掌握springboot 中如何配置线程池的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注天达云行业资讯频道,感谢各位的阅读!