1.启动类添加注解
@EnableScheduling
2.进行线程池config配置
//允许使用异步方法
@EnableAsync
@Configuration
public class ExecutorCreated {
@Bean("tread")
public Executor createdExecutor(){
//创建线程池任务执行器对象
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//配置程池线中核心线程数量
executor.setCorePoolSize(10);
//配置线程池中最大线程数量
executor.setMaxPoolSize(100);
//配置队列的长度
executor.setQueueCapacity(200);
//配置线程名称前缀
executor.setThreadNamePrefix("executor");
//配置拒绝策略,在任务被拒绝添加后会调用当前线程池的所在的线程去执行被拒绝的任务
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//实例化执行者
executor.initialize();
return executor;
}
}
3.创建需要在多线程环境中运行的Service方法
@Service
public class HelloService {
//使用异步方法
@Async("tread")
public void hello(){
DateFormat df =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Thread.sleep(5000);
System.out.println("执行方法的线程: "+Thread.currentThread().getName());
System.out.println("执行时间: "+df.format(new Date()));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
4.在controller层进行调用执行访问
@GetMapping("hello")
public void hello(){
helloService.hello();
}
5.输出结果
总结:
我这边的service方法中添加了5秒延迟,在快速多次发送请求后发现并没有出现等待现象,而是不同的线程在异步的执行任务,线程池使用成功!