当前位置: 首页 > news >正文

Springboot自定义线程池实现多线程任务

1. 在启动类添加@EnableAsync注解

在这里插入图片描述

2.自定义线程池

package com.bt.springboot.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;import java.util.concurrent.Executor;/*** @author zkx* @Date 2024/1/19 17:17*/
@Configuration
public class AsyncConfig {@Bean("asyncTaskExecutor")public Executor asyncTaskExecutor() {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();// 核心线程数executor.setCorePoolSize(10);// 最大线程数executor.setMaxPoolSize(20);// 队列最大长度
//		executor.setQueueCapacity(10000);// 设置线程名executor.setThreadNamePrefix("Async-Task");return executor;}}

3.编写要异步执行的任务

package com.bt.springboot.task;import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;/*** @author zkx* @Date 2024/1/29 17:14*/
@Slf4j
@Component
public class UserTask {@Async("asyncTaskExecutor")public void getUserInfo(Long userId){log.info("当前线程:{}", Thread.currentThread().getName());log.info("获取用户Id为{}的信息:", userId);}
}

4.编写测试方法

package com.bt.springboot;import com.bt.springboot.task.UserTask;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import java.util.Arrays;
import java.util.List;/*** @author zkx* @Date 2024/1/29 17:17*/
@Slf4j
@SpringBootTest
@RunWith(SpringRunner.class)
public class ThreadPoolTest {@Autowiredprivate UserTask userTask;@Testpublic void test(){List<Long> userIds = Arrays.asList(1L,2L,3L,4L,5L,6L,7L,8L,9L,10L);for (Long userId : userIds) {userTask.getUserInfo(userId);}}
}

5.运行测试方法

6.打印日志结果

在这里插入图片描述

http://www.lryc.cn/news/290893.html

相关文章:

  • linux离线升级openssh方法
  • (五)MySQL的备份及恢复
  • VitePress-04-文档中的表情符号的使用
  • Redis客户端之Redisson(二)Redisson组件
  • 用Visual Studio Code创建JavaScript运行环境【2024版】
  • spring-web搭建
  • C++ 之LeetCode刷题记录(二十三)
  • 在ubuntu上在安装Squid代理服务器
  • 如何解决 MySQL 的 socket 错误
  • 5G智慧钢铁厂数字孪生三维可视化,推进钢铁新型工业化数字化转型
  • 万户 ezOFFICE DocumentEditExcel.jsp SQL注入漏洞
  • OpenCV 2 - 矩阵的掩膜操作
  • linux -- 内存管理 -- 页面分配器
  • StarRocks-3.1.0 单节点部署
  • 2023美赛A题之Lotka-Volterra【完整思路+代码】
  • 关于如何将Win幻兽帕鲁服务端存档转化为单人本地存档的一种方法(无损转移)
  • 计算机网络——IP协议
  • Linux命令-ar命令(建立或修改备存文件,或是从备存文件中抽取文件)
  • flask基于python的个人理财备忘录记账提醒系统vue
  • 【leetcode题解C++】257.二叉树的所有路径 and 404.左叶子之和 and 112.路径总和
  • Linux——文本编辑器Vim
  • 以“美”为鉴,探寻香港比特币现货ETF的未来发展
  • Unity项目打包的方法(之一)
  • 如何安装MySQL
  • 如何编写.gitignore文件
  • U-Boot学习(7):内核启动之bootz启动zImage源码分析
  • [GN] DP学习笔记板子
  • GLog开源库使用
  • 微信小程序如何实现点击上传图片功能
  • Windows Qt C++ VTK 绘制三维曲线