springboot阻塞式异步并发使用
1.异步线程池配置
@Configuration
@Slf4j
public class TaskPoolConfig {
@Bean("asyncTaskExcutor")
public Executor asyncTaskExcutor(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//核心线程池大小
executor.setCorePoolSize(5);
//最大线程数
executor.setMaxPoolSize(10);
//队列容量
executor.setQueueCapacity(50);
//活跃时间
executor.setKeepAliveSeconds(100);
//线程名字前缀
executor.setThreadNamePrefix("MyExecutor-");
// setRejectedExecutionHandler:当pool已经达到max size的时候,如何处理新任务
// CallerRunsPolicy:不在新线程中执行任务,而是由调用者所在的线程来执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
executor.initialize();
return executor;
}
}
2.开启异步以及定义异步方法
@SpringBootApplication
@EnableAsync
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
@Component
@Slf4j
public class AsyncTask {
@Async("asyncTaskExcutor")
public Future<String> asyncTask2() {
String threadName=Thread.currentThread().getName();
long startTime=System.currentTimeMillis();
log.info("{}开始执行异步方法",threadName);
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("{}结束执行异步方法",threadName);
long endTIme=System.currentTimeMillis();
log.info("{}花费时间{}秒",threadName,(endTIme-startTime)/1000);
return new AsyncResult<>(threadName+"异步任务完成");
}
}
3.测试
public void testAsync2() {
List<Future<String>> taskList=new ArrayList<>();
for (int i = 0; i < 3; i++) {
Future<String> task = asyncTask.asyncTask2();
taskList.add(task);
}
while (true){
boolean flag=true;
for (Future<String> task : taskList) {
if(!task.isDone()){
flag=false;
}
}
if(flag){
break;
}
}
taskList.forEach(task-> {
try {
System.out.println(task.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
});
System.out.println("主线程调用结束");
}
本文来自博客园,作者:iaxusyy,转载请注明原文链接:https://www.cnblogs.com/ww-NoBugs/p/15824820.html
分类:
框架和第三方轮子
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)