/**PageBeginHtml Block Begin **/ /***自定义返回顶部小火箭***/ /*生成博客目录的JS 开始*/ /*生成博客目录的JS 结束*/

spring-boot 多线程

* 博客文章部分截图及内容来自于学习的书本及相应培训课程以及网络其他博客,仅做学习讨论之用,不做商业用途。
* 如有侵权,马上联系我,我立马删除对应链接。
* @author Alan
* @Email no008@foxmail.com



复制代码
  1 //配置类
  2 
  3 package test;
  4 
  5 import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
  6 import org.springframework.context.annotation.ComponentScan;
  7 import org.springframework.context.annotation.Configuration;
  8 import org.springframework.scheduling.annotation.AsyncConfigurer;
  9 import org.springframework.scheduling.annotation.EnableAsync;
 10 import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
 11 
 12 import java.util.concurrent.Executor;
 13 
 14 @Configuration
 15 @ComponentScan("test")
 16 @EnableAsync
 17 public class TaskExecutorConfig implements AsyncConfigurer{
 18 
 19     @Override
 20     public Executor getAsyncExecutor() {
 21         ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
 22         taskExecutor.setCorePoolSize(5);
 23         taskExecutor.setMaxPoolSize(10);
 24         taskExecutor.setQueueCapacity(25);
 25         taskExecutor.initialize();
 26         return taskExecutor;
 27     }
 28 
 29     @Override
 30     public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
 31         return null;
 32     }
 33 }
复制代码


复制代码
  1 //任务执行类
  2 
  3 package test;
  4 
  5 import org.springframework.scheduling.annotation.Async;
  6 import org.springframework.stereotype.Service;
  7 
  8 @Service
  9 public class AsyncTaskService {
 10 
 11     @Async
 12     public void executeAsyncTask(Integer i) {
 13         System.out.println("执行异步任务:" + i);
 14     }
 15 }
复制代码


复制代码
  1 //运行
  2 
  3 package test;
  4 
  5 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
  6 
  7 public class Application {
  8 
  9     public static void main(String[] args) {
 10         AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskExecutorConfig.class);
 11 
 12         AsyncTaskService asyncTaskService = context.getBean(AsyncTaskService.class);
 13         for (int i = 0; i < 20; i++) {
 14             asyncTaskService.executeAsyncTask(i);
 15         }
 16         context.close();
 17     }
 18 }
复制代码







本文出自于:hacpai

posted @   一品堂.技术学习笔记  阅读(1869)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示