版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fantasic_van/article/details/81662896
一般来说,任务执行都是同步的、
Spring通过TaskExecutor来实现多线程,异步执行,通过注解@EnableAsync来开启异步任务执行的支持
下面进行测试:
一、新建一个maven项目,并导入spring的包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.3.RELEASE</version>
</dependency>
二、创建自己的配置类,实现AsyncConfigurer接口
package cn.van.taskExcutor;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@Configuration
@ComponentScan("cn.van.taskExcutor")
@EnableAsync //开启对异步任务的支持
public class TaskExecutorConfig 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;
}
}
三、创建自己的任务类
package cn.van.taskExcutor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
@Async //放在类上,表明该类中所有方法都是异步执行
public class AsyncTaskService {
public void executeAysncTask1(Integer i){
System.out.println("executeAysncTask1: " + i);
}
public void executeAysncTask2(Integer i){
System.out.println("executeAysncTask2: " + i);
}
}
四、测试
package cn.van.taskExcutor;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TaskExecutor {
public static void main(String[] args) {
AnnotationConfigApplicationContext application
= new AnnotationConfigApplicationContext(TaskExecutorConfig.class);
AsyncTaskService service = application.getBean(AsyncTaskService.class);
for(int i=0;i<10;i++){
service.executeAysncTask1(i);
service.executeAysncTask2(i+1);
}
application.close();
}
}
如果是同步执行,那同一个task, 得出的数是比前一个大1的。
这里并没有体现,因为是异步执行。