springboot+多线程简单实现

本文详细介绍了如何在SpringBoot环境中配置线程池以执行异步任务,包括创建ThreadConfig类,设置线程池参数,以及在service中使用@Async注解实现异步方法调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文链接: https://segmentfault.com/a/1190000017924478
         <!--一个博主专栏付费入口结束-->
        <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-4a3473df85.css">
                                    <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-4a3473df85.css">
            <div class="htmledit_views" id="content_views">
                                        
<div class="article fmt article__content">

搭建springboot环境
创建ThreadConfig


 
  1. /**
  2. * 线程
  3. *
  4. * @author zhoumin
  5. * @create 2018-09-18 13:58
  6. */
  7. @Configuration
  8. @EnableAsync
  9. public class ThreadConfig implements AsyncConfigurer{
  10. @Override
  11. public Executor getAsyncExecutor() {
  12. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  13. executor.setCorePoolSize( 8);
  14. executor.setMaxPoolSize( 1000);
  15. executor.setQueueCapacity( 500);
  16. executor.setKeepAliveSeconds( 30000);
  17. executor.initialize();
  18. return executor;
  19. }
  20. @Override
  21. public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
  22. return null;
  23. }
  24. }

创建service和接口

void test(int i);
 

service实现类


 
  1. @Override
  2. @Async
  3. public void test(int i) {
  4. System.out.println( "线程" + Thread.currentThread().getName() + " 执行异步任务:" + i);
  5. }

测试:


 
  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest
  3. public class BaseTest {
  4. }

 
  1. /**
  2. * @author zhoumin
  3. * @create 2018-09-18 14:12
  4. */
  5. public class ThreadTest extends BaseTest{
  6. @Autowired
  7. private DeviceStatisticsTaskService deviceStatisticsTaskService;
  8. @org.junit. Test
  9. public void threadTest () {
  10. for ( int i = 0; i < 5000; i++) {
  11. deviceStatisticsTaskService.test(i);
  12. }
  13. }
  14. }
            </div>
                                  </div>
                </div>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值