springboot异步线程池

本文介绍了如何在Spring框架中配置异步线程池来实现并发任务处理。通过定义核心线程数、最大线程数及队列容量等参数,创建了一个可自定义的线程池,用于异步执行业务逻辑。

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

配置异步线程池

package com.sudy.chargerpad.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {

    @Nullable
    @Override
    public Executor getAsyncExecutor() {
        //定义线程池
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        //核心线程数
        taskExecutor.setCorePoolSize(10);
        //线程池最大线程数
        taskExecutor.setMaxPoolSize(30);
        //线程队列最大线程数
        taskExecutor.setQueueCapacity(200);
        //初始化
        taskExecutor.initialize();
        return taskExecutor;
    }
}

测试service

package com.sudy.chargerpad.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncService {
    @Async
    public void async(){
        System.out.println("线程名称:"+Thread.currentThread().getName());
    }
}

测试controller

   @Autowired
    private AsyncService asyncService;
    @GetMapping("/async")
    public String async(){
        System.out.println("c 线程名称:"+Thread.currentThread().getName());
        asyncService.async();
        return "async";
    }

测试结果控制器方法和service方法使用两个线程

c 线程名称:http-nio-8092-exec-1

线程名称:ThreadPoolTaskExecutor-1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值