springboot中使用线程池

1.什么场景下使用线程池?

在异步的场景下,可以使用线程池

不需要同步等待,

不需要管上一个方法是否执行完毕,你当前的方法就可以立即执行

我们来模拟一下,在一个方法里面执行3个子任务,不需要相互等待

2.代码引入线程池配置类

java 复制代码
package com.example.demo2.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;

/**
 * 线程池工具类
 */
@Configuration
public class XianChengConfig {


    /**
     * 创建线程池放入ioc容器
     */
    @Bean
    public ThreadPoolExecutor threadPoolExecutor(){
        //核心线程数
        int corePoolSize = 10;
        //最大线程数
        int maximumPoolSize =10;
        //线程存活时间单位
        long keepAliveTime = 60;
        //线程存活时间 秒
        TimeUnit unit = TimeUnit.SECONDS;
        //任务队列
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(100);
        //线程工厂
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        //拒绝策略 谁调用谁执行
        RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy();
        ThreadPoolExecutor bean = new ThreadPoolExecutor( corePoolSize,
         maximumPoolSize,
         keepAliveTime,
         unit,
         workQueue,
         threadFactory,
         handler);
        return bean;
    }
}

3.使用线程池

java 复制代码
package com.example.demo2.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ThreadPoolExecutor;

@RestController
public class TestController {

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;


    @GetMapping("/test")
    public String test() {
        System.out.println("---------------方法1------------------");
        threadPoolExecutor.execute(()->{
            //异步执行 角色任务
            syncRole();
        });

        System.out.println("---------------方法2------------------");

        threadPoolExecutor.execute(()->{
            //异步执行 用户任务
            syncUser();
        });

        System.out.println("----------------方法3-----------------");
        threadPoolExecutor.execute(()->{
            //异步执行 菜单任务
            syncMenu();
        });

        return "ok";
    }


    private void syncRole(){
        System.out.println("开始获取角色,线程名称:"+Thread.currentThread().getName());
        try {
            //阻塞4秒
            Thread.sleep(1000*4);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("结束获取角色,线程名称:"+Thread.currentThread().getName());
    }

    private void syncUser(){
        System.out.println("开始获取用户,线程名称:"+Thread.currentThread().getName());
        try {
            //阻塞3秒
            Thread.sleep(1000*3);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("结束获取用户,线程名称:"+Thread.currentThread().getName());
    }

    private void syncMenu(){
        System.out.println("开始获取菜单,线程名称:"+Thread.currentThread().getName());
        try {
            //阻塞2秒
            Thread.sleep(1000*2);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("结束获取菜单,线程名称:"+Thread.currentThread().getName());
    }
}

http://localhost:8080/test

可以看到,角色没有执行完,用户开始执行

用户没有执行完,菜单也开始执行

3个任务不需要等待其他方法执行完,才去执行自己的任务

这就是异步的场景,这种场景下就可以使用多线程

相关推荐
金牌服务刘几秒前
主数据平台下游系统过多如何下发数据?
后端·微服务·连续集成
remaindertime9 分钟前
(八)Spring Cloud Alibaba 2023.x:网关统一鉴权与登录实现
后端·微服务
IT_陈寒9 分钟前
Java性能优化:10个让你的Spring Boot应用提速300%的隐藏技巧
前端·人工智能·后端
bug攻城狮16 分钟前
Spring Boot Banner
java·spring boot·后端
黑马源码库miui5208636 分钟前
JAVA同城打车小程序APP打车顺风车滴滴车跑腿源码微信小程序打车源码
java·微信·微信小程序·小程序·uni-app
MadPrinter42 分钟前
SpringBoot学习日记 Day11:博客系统核心功能深度开发
java·spring boot·后端·学习·spring·mybatis
dasseinzumtode43 分钟前
nestJS 使用ExcelJS 实现数据的excel导出功能
前端·后端·node.js
淦出一番成就1 小时前
Java反序列化接收多种格式日期-JsonDeserialize
java·后端
Java中文社群1 小时前
Hutool被卖半年多了,现状是逆袭还是沉寂?
java·后端
程序员蜗牛1 小时前
9个Spring Boot参数验证高阶技巧,第8,9个代码量直接减半!
后端