本文主要是介绍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("主线程调用结束");
}
这篇关于springboot阻塞式异步并发使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!