一,配置异步线程池
@EnableAsync //启动异步线程
public class WebConfig implements WebMvcConfigurer {
@Bean("taskExecutor")
public ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(10);
taskExecutor.setMaxPoolSize(20);
taskExecutor.setQueueCapacity(100);
taskExecutor.setThreadNamePrefix("asyncTask");
return taskExecutor;
}
}
二,使用
方法1:注解 @Async
@Async
public void test(){
System.out.println("线程ID:" + Thread.currentThread().getId() + "线程名字:" +Thread.currentThread().getName()+"执行异步任务:");
}
方法2:使用对象
public class Test{
@Autowired
@Qualifier("taskExecutor")
public ThreadPoolTaskExecutor executor;
public void test2() {
executor.execute(()->{
System.out.println("线程ID:" + Thread.currentThread().getId() + "线程名字:" +Thread.currentThread().getName()+"执行异步任务:");
});
}
}
以上是不返回值的情况;
execute(),执行一个任务,没有返回值submit(),提交一个线程任务,有返回值
返回值的
@Async
public Future<String> executeAsyncPlus(Integer i) throws Exception {
System.out.println("线程ID:" + Thread.currentThread().getId() +"线程名字:" +Thread.currentThread().getName()+ "执行异步有返回的任务:" + i);
return new AsyncResult<>("success:"+i);
}
Future<String> result = service.executeAsyncPlus(i);
result.get();
文章介绍了如何在SpringBoot应用中配置和使用ThreadPoolTaskExecutor来实现异步任务。通过@EnableAsync启用异步处理,然后配置线程池参数,如核心线程数、最大线程数和队列容量。文中提供了两种使用方式:一种是直接在方法上使用@Async注解,另一种是通过注入线程池对象执行任务。此外,还展示了如何处理异步任务的返回值,使用Future来获取结果。
1483

被折叠的 条评论
为什么被折叠?



