Spring通过任务执行器(TaskExecutor)来实现多线程和并发。可使用ThreadPoolTaskExecutor来实现;
1.利用@EnableAsync开启异步任务支持
2.配置实现AsyncConfigurer接口的类并重写getAsyncExecutor方法得到基于线程池的TaskExecutor
@Configuration
@EnableAsync
public class TaskConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(5);
taskExecutor.setMaxPoolSize(10);
taskExecutor.setQueueCapacity(25);
taskExecutor.initialize();
return taskExecutor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
任务类
@Service
@Async //可用于具体方法 类上标识此类方法全部是异步方法
public class AsyncTaskService {
public void executeTask(Integer i){
System.err.println("异步任务..."+i);
}
public void executeTask2(Integer i){
System.err.println("异步任务2..."+i);
}
}
执行
AsyncTaskService service = context.getBean(AsyncTaskService.class);
for(int i=0;i<10;i++){
service.executeTask(i);
service.executeTask2(i);
}
结果
异步任务...0
异步任务2...0
异步任务2...2
异步任务...3
异步任务...2
异步任务...1
异步任务2...1
异步任务2...5
异步任务...6
异步任务2...6
异步任务...7
异步任务2...7
异步任务...8
异步任务2...8
异步任务...9
异步任务2...9
异步任务...5
异步任务2...4
异步任务...4
异步任务2...3
并发执行而不是顺序执行