SpringBoot 线程池(二):使用异步线程池
SpringBoot 线程池(二):使用异步线程池
1 创建异步线程池配置
1.1 配置线程池属性
在 application.properties
配置文件中添加异步线程池的相关属性
# 异步线程池相关属性
asyncThreadPool.corePoolSize = 10
asyncThreadPool.maxPoolSize = 20
asyncThreadPool.queueCapacity = 50
asyncThreadPool.keepAliveSeconds = 60
asyncThreadPool.threadNamePrefix = async-task-thread-pool-%d
1.2 创建线程池配置类
创建 AsyncConfig
类并添加 @Configuration
注释,完整配置如下:
/**
* 异步线程池配置
*/
@Configuration
public class AsyncConfig {
@Value("${asyncThreadPool.corePoolSize}")
private int corePoolSize;
@Value("${asyncThreadPool.maxPoolSize}")
private int maxPoolSize;
@Value("${asyncThreadPool.queueCapacity}")
private int queueCapacity;
@Value("${asyncThreadPool.keepAliveSeconds}")
private int keepAliveSeconds;
@Value("${asyncThreadPool.threadNamePrefix}")
private String threadNamePrefix;
@Bean
public Executor asyncExecutor() {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setCorePoolSize(corePoolSize);
threadPoolTaskExecutor.setMaxPoolSize(maxPoolSize);
threadPoolTaskExecutor.setQueueCapacity(queueCapacity);
threadPoolTaskExecutor.setKeepAliveSeconds(keepAliveSeconds);
threadPoolTaskExecutor.setThreadNamePrefix(threadNamePrefix);
threadPoolTaskExecutor.initialize();
return threadPoolTaskExecutor;
}
}
2 创建任务
2.1 创建异步任务类 SyncTask
创建同步任务类 AsyncTask
,添加 @Component
注释
2.2 创建需要执行的任务
为了测试方便,只打印一行信息,异步任务需要添加 @Async
注解。
@Async("asyncExecutor")
public void execute() {
try {
System.out.println(Thread.currentThread().getName() + ":async execute task...");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
2.3 SyncTask 类完整代码
@Component
public class AsyncTask {
@Async("asyncExecutor")
public void execute() {
try {
System.out.println(Thread.currentThread().getName() + ":async execute task...");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
2 创建单元测试进行测试
本次使用 JUnit5
进行测试,完整代码如下:
2.1 无返回值
@SpringBootTest
class StudyApplicationTests {
@Autowired
AsyncTask asyncTask;
@Test
public void asyncWithThreadPool() {
System.out.println("start execute task...");
long startTime = System.currentTimeMillis();
// 无返回值
for (int i = 0; i < 10 ; i++) {
asyncTask.execute();
}
long endTime = System.currentTimeMillis();
System.out.println("total time:" + (endTime - startTime));
}
}
打印日志结果:
start execute task...
total time:5
async-task-thread-pool-1:async execute task...
async-task-thread-pool-10:async execute task...
async-task-thread-pool-8:async execute task...
async-task-thread-pool-6:async execute task...
async-task-thread-pool-5:async execute task...
async-task-thread-pool-7:async execute task...
async-task-thread-pool-4:async execute task...
async-task-thread-pool-9:async execute task...
async-task-thread-pool-3:async execute task...
async-task-thread-pool-2:async execute task...