在spring boot中实现线程池

在 Spring Boot 中实现线程池

一、添加依赖

首先,确保您的项目中添加了相关的依赖。如果您使用 Maven 构建项目,在  pom.xml  文件中添加以下依赖:

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-web</artifactId>

</dependency>

<dependency>

    <groupId>org.springframework</groupId>

    <artifactId>spring-core</artifactId>

    <version>5.x.x.RELEASE</version> 

</dependency>

二、创建线程池配置类

 创建一个配置类来配置线程池,示例如下:

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

@Configuration

public class ThreadPoolConfig {

    @Bean

    public Executor taskExecutor() {

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

        executor.setCorePoolSize(5); 

        executor.setMaxPoolSize(10); 

        executor.setQueueCapacity(25);

        executor.setThreadNamePrefix("MyThread-"); 

        executor.initialize();

        return executor;

    }

}

 在上述代码中,创建了一个  ThreadPoolTaskExecutor  对象,并设置了核心线程数、最大线程数、队列容量和线程名称前缀等属性。

 三、使用线程池

 在需要使用线程池的地方,注入刚刚配置的线程池  Executor  对象,然后使用它来执行任务,示例如下:

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.scheduling.annotation.Async;

import org.springframework.stereotype.Service;

 

@Service

public class MyService {

 

    @Autowired

    private Executor taskExecutor;

 

    @Async("taskExecutor")

    public void doTask() {

        // 在这里编写您的任务逻辑

        System.out.println("正在执行任务...");

    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值