注解实现异步多线程非阻塞
文件结构:
环境jar包:
jdk: jdk1.8.0_121(32位)
pom:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.10.RELEASE</version>
</dependency>
配置类 TaskExecutorConfig:
package com.Async;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
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 org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import java.util.concurrent.Executor;
@Configuration
@EnableAsync //启用异步
@ComponentScan("com.Async")
public class TaskExecutorConfig implements AsyncConfigurer {//实现异步接口
//异步线程池配置
public Executor getAsyncExecutor(){
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setCorePoolSize(5);//常规线程数量
threadPoolTaskExecutor.setMaxPoolSize(10);//最大线程数量
threadPoolTaskExecutor.setQueueCapacity(100);//等待执行线程队列数量
threadPoolTaskExecutor.initialize();//构建
return threadPoolTaskExecutor;
}
}
异步方法类 AsyncTaskService:
package com.Async;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncTaskService {
@Async //注解异步方法
public void execute(Integer i) {
System.out.println("执行异步输出execute: "+i);
}
@Async
public void executeAsyncTaskPlus(Integer i){
System.out.println("执行异步输出executeAsyncTaskPlus: "+i);
}
}
测试类Main:
package com.Async;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String [] args){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(TaskExecutorConfig.class);
AsyncTaskService bean = applicationContext.getBean(AsyncTaskService.class);
for (int i = 0;i < 10; i++){
bean.execute(i);
bean.executeAsyncTaskPlus(i);
}
applicationContext.close();
}
}
输出结果: