SpringBoot原生异步调用方法(线程池方法)

SpringBoot原生异步调用步骤

  • 在启动类或者是线程池配置类上添加@EnableAsync注解,表示启用异步处理
  • 在Configuration配置类里将线程池添加到IOC容器里(一般使用@Bean和@Qualifier这两个注解)
  • 在需要使用线程池异步调用的方法上添加@Aysnc注解,value值给之前在配置类里面定义的该Bean的名字.

案例:
(1)首先创建一个空的SpringBoot项目
(2)然后配置类如下

/**
 * <p>
 * description
 * </p>
 *
 * @Author HONG.SHAO@hand-china.com 2020/8/27 15:50
 **/
@Configuration
@EnableAsync
public class JustConfig {

    @Bean
    @Qualifier("justAysncTaskExecutor")
    public AsyncTaskExecutor asyncTaskExecutor(){
        ThreadPoolTaskExecutor threadPoolExecutor = new ThreadPoolTaskExecutor();
        threadPoolExecutor.setThreadGroupName("just-executor");
        threadPoolExecutor.setCorePoolSize(2);
        threadPoolExecutor.setMaxPoolSize(8);
        threadPoolExecutor.setQueueCapacity(12);
        return threadPoolExecutor;
    }
}

(3)最后编写需要异步执行的方法

@Service
public class AsyncService {
    Logger logger = LoggerFactory.getLogger(AsyncService.class);
    @Async(value = "justAysncTaskExecutor")
    public void asyncTask(){
        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            logger.info(Thread.currentThread().getName()+"----正在处理----"+i);
        }
    }
}

(4)最后就是测试

@SpringBootTest
class AsyncmultithreadApplicationTests {

    @Autowired
    private AsyncService asyncService;
    @Test
    void contextLoads() {
        asyncService.asyncTask();
        asyncService.asyncTask();
        asyncService.asyncTask();
        System.out.println("--------主线程执行完毕");
    }
}

(5)运行结果
在这里插入图片描述
可以看出,当主线程执行退出后,线程池里面的线程并没有随着主线程结束而终止,当线程池中线程执行完毕后线程池会自行shutdown,不需要我们开发人员去处理。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值