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 {
   

	@Autowired
	private UserTask userTask;

	@Test
	public 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.打印日志结果

在这里插入图片描述

相关推荐

  1. Springboot定义线ThreadPoolTaskExecutor

    2024-01-30 22:30:03       32 阅读
  2. SpringBoot集成定义线

    2024-01-30 22:30:03       35 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-30 22:30:03       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-30 22:30:03       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-30 22:30:03       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-30 22:30:03       18 阅读

热门阅读

  1. MySQL学习笔记01

    2024-01-30 22:30:03       29 阅读
  2. C++ STL库之Vector简介及例题(哈希表)(一)

    2024-01-30 22:30:03       31 阅读
  3. python中for循环的几个现象

    2024-01-30 22:30:03       34 阅读
  4. rust 泛型

    2024-01-30 22:30:03       44 阅读