SpringBoot多线程

Spring是通过任务执行器(TaskExecutor)来实现多线程和并发编程,使用ThreadPoolTaskExecutor来创建一个基于线城池的TaskExecutor。在使用线程池的大多数情况下都是异步非阻塞的。我们配置注解@EnableAsync可以开启异步任务。然后在实际执行的方法上配置注解@Async上声明是异步任务。
在这里插入图片描述

创建一个配置类:

首先使用@EnableAsync来开启Springboot对于异步任务的支持

配置类实现接口AsyncConfigurator,返回一个ThreadPoolTaskExecutor线程池对象

@Configuration
@EnableAsync //开启异步
public class TaskConfig implements AsyncConfigurer {
    
    @Override
    public Executor getAsyncExecutor() {
        // 设置线程数
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        //核心线程数
        taskExecutor.setCorePoolSize(25);
        //最大线程数
        taskExecutor.setMaxPoolSize(50);
        //阻塞队列
        taskExecutor.setQueueCapacity(100);
        //初始化线程
        taskExecutor.initialize();
        return taskExecutor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }
}

ThredPoolTaskExcutor的处理流程
当池子大小小于corePoolSize,就新建线程,并处理请求
当池子大小等于corePoolSize,把请求放入workQueue中,池子里的空闲线程就去workQueue中取任务并处理
当workQueue放不下任务时,就新建线程入池,并处理请求,如果池子大小撑到了maximumPoolSize,就用RejectedExecutionHandler来做拒绝处理
当池子的线程数大于corePoolSize时,多余的线程会等待keepAliveTime长时间,如果无请求可处理就自行销毁

HelloController

@RestController
public class HelloController {
    @Autowired
    private HelloService helloService;

    @RequestMapping("test001")
    public Object test01() throws InterruptedException {
        System.out.println("进入方法体");
        for (int i = 0; i < 10; i++) {
            helloService.asyncTask01(i);
        }
        return "OK";
    }
}

HelloService

public interface HelloService {
    void asyncTask01(int i) throws InterruptedException;
}

HelloServiceImpl

通过@Async注解表明该方法是异步方法,如果注解在类上,那表明这个类里面的所有方法都是异步的。

@Service
public class HelloServiceImpl implements HelloService {
    
    @Async  //声明方法为异步方法
    @Override
    public void asyncTask01(int i) throws InterruptedException {
        Thread.sleep(1000L);
        System.out.println(i);
    }
}

测试:

访问:http://localhost:8082/test001

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值