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个任务不需要等待其他方法执行完,才去执行自己的任务

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

相关推荐
源代码•宸几秒前
Golang原理剖析(程序初始化、数据结构string)
开发语言·数据结构·经验分享·后端·golang·string·init
韩立学长几秒前
【开题答辩实录分享】以《以体验为中心的小学古诗互动学习App的设计及实现》为例进行选题答辩实录分享
java·spring·安卓
萤丰信息4 分钟前
科技赋能智慧园区:解码绿色转型的“数字密码”
java·大数据·人工智能·科技·安全·智慧城市·智慧园区
小鸡脚来咯14 分钟前
RESTful API 面试详解
后端·面试·restful
吴巴格16 分钟前
springboot引用其他中间件,如何确定版本
spring boot·后端·中间件
码农阿豪18 分钟前
远程调试不再难!Remote JVM Debug+cpolar 让内网 Java 程序调试变简单
java·开发语言·jvm
stillaliveQEJ22 分钟前
【JavaEE】Spring AOP(二)
java·spring·java-ee
IT_陈寒23 分钟前
Vue3性能优化实战:5个被低估的API让我减少了40%的代码量
前端·人工智能·后端
vx_bisheyuange27 分钟前
基于SpringBoot的旅游管理系统
前端·javascript·vue.js·spring boot·毕业设计
岁岁种桃花儿29 分钟前
Spring Boot项目核心配置:parent父项目详解(附实操指南)
java·spring boot·spring