- 注解启动类
@EnableAsync
@SpringBootApplication
public class LocustRunnerApplication {
public static void main(String[] args) {
SpringApplication.run(LocustRunnerApplication.class, args);
}
}
- 添加线程池配置
@Configuration
public class AsyncConfig {
@Bean
public Executor asyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(4);
executor.setMaxPoolSize(8);
executor.setQueueCapacity(200);
executor.setThreadNamePrefix("LocustTask-");
executor.initialize();
return executor;
}
}
- 标注异步方法-不带返回值
@Async
public void asyncMethod() {
try {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " asyncMethod: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
- 标注异步方法-不带返回值
@Async
public Future<String> asyncMethodWithReturn() {
try {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " asyncMethodWithReturn: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return new AsyncResult<>(Thread.currentThread().getName() + " asyncMethodWithReturn: done");
}
线程池的调用过程
- 核心线程池未满时: 接收任务,创建线程并执行该任务。
- 核心线程池已满时: 接收任务,任务进入等待队列等待。
- 核心线程池满且等待队列也满时: 接收任务,并创建线程执行该任务。
- 核心线程满,等待队列满且最大线程池也满时: 接收任务,按丢弃策略处理该任务。
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。