springboot将schedule多线程执行
时间: 2023-08-16 10:03:24 浏览: 108
在Spring Boot中使用Schedule多线程执行,可以通过使用@Async注解和TaskExecutor来实现。具体步骤如下:
1. 在主类上添加@EnableAsync注解启用异步执行
```
@SpringBootApplication
@EnableAsync
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
```
2. 在需要异步执行的方法上添加@Async注解
```
@Service
public class MyService {
@Async
public void doSomething() {
// 执行任务
}
}
```
3. 配置TaskExecutor,指定线程池大小等参数
```
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(100);
executor.setThreadNamePrefix("MyExecutor-");
executor.initialize();
return executor;
}
}
```
4. 在需要调用异步方法的地方注入MyService,并调用doSomething方法
```
@RestController
public class MyController {
@Autowired
private MyService myService;
@GetMapping("/do")
public String do() {
myService.doSomething();
return "OK";
}
}
```
这样配置后,调用do方法时,doSomething方法就会在后台线程池中异步执行。注意,@Async注解只有在被Spring容器管理的类中才有效。
阅读全文