9、springboot-线程池

本文详细介绍了如何在Spring Boot项目中手动配置和使用线程池,以应对疫情大数据平台可能出现的高并发访问需求。通过启用@EnableAsync注解,创建ThreadPoolTaskExecutor类,定义线程池参数,并在任务类中调用线程池服务,实现高效的任务调度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

疫情大数据平台可能会出现短时大量访问的情况,就需要线程池进行处理,本篇主要描述手动实现线程池

实现:

首先启动类需要添加这个注解@EnableAsync

@SpringBootApplication
@EnableAsync
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}
	@Bean
	public RestTemplate restTemplate() {
		return new RestTemplate();
	}
}

然后,新增threadPoolTaskExecutor类,用于创建线程池

@Configuration
@EnableAsync
public class ThreadExecutorConfig {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private int corePoolSize = 20;
    private int maxPoolSize = 20;
    private int queueCapacity = 20;
    @Bean
    public Executor threadPoolTaskExecutor(){

        System.out.println("创建线程池");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix("threadPoolTaskExecutor-》》》");

        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        executor.initialize();
        return executor;
    }

使用线程池

任务类

@Component
public class test {
    @Async("threadPoolTaskExecutor")
    public void testThread() throws InterruptedException {
        System.out.println("内部1"+Thread.currentThread().getName());

        System.out.println("2s执行方法睡眠前");
        Thread.sleep(2000);
        System.out.println("2s执行方法睡眠后");

    }
    @Async("threadPoolTaskExecutor")
    public void testThread1() throws InterruptedException {
        System.out.println("内部2"+Thread.currentThread().getName());

        System.out.println("10s执行方法睡眠前");
        Thread.sleep(10000);
        System.out.println("10s执行方法睡眠后");

    }

}

补充线程池代码

新增一个配置类

public class MyThreadPoolTaskExecutor extends ThreadPoolTaskExecutor {
 
    Logger logger = LoggerFactory.getLogger(MyThreadPoolTaskExecutor.class);
 
    @Override
    public void execute(Runnable task) {
        logThreadPoolStatus();
        super.execute(task);
    }
 
    @Override
    public void execute(Runnable task, long startTimeout) {
        logThreadPoolStatus();
        super.execute(task, startTimeout);
    }
 
    @Override
    public Future<?> submit(Runnable task) {
        logThreadPoolStatus();
        return super.submit(task);
    }
 
    @Override
    public <T> Future<T> submit(Callable<T> task) {
        logThreadPoolStatus();
        return super.submit(task);
    }
 
    @Override
    public ListenableFuture<?> submitListenable(Runnable task) {
        logThreadPoolStatus();
        return super.submitListenable(task);
    }
 
    @Override
    public <T> ListenableFuture<T> submitListenable(Callable<T> task) {
        logThreadPoolStatus();
        return super.submitListenable(task);
    }
 
 
    private void logThreadPoolStatus() {
        logger.info("核心线程数:{}, 最大线程数:{}, 当前线程数: {}, 活跃的线程数: {}",
                getCorePoolSize(), getMaxPoolSize(), getPoolSize(), getActiveCount());
    }
}

补充bean

@Bean
    public Executor myThreadPool() {
       
        int corePoolSize = 5;
      
        int maxPoolSize = 5;
       
        int queueCapacity = 2000;
       
        long keepAliveTime = 30;
       
        String threadNamePrefix = "myThreadPool-->";
      
        RejectedExecutionHandler rejectedExecutionHandler = new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                throw new RejectedExecutionException("自定义的RejectedExecutionHandler");
            }
        };
      
        ThreadFactory threadFactory = new ThreadFactory() {
            private int i = 1;
 
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName(threadNamePrefix + i);
                i++;
                return thread;
            }
        };
      
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maxPoolSize,
                keepAliveTime, TimeUnit.SECONDS, new LinkedBlockingQueue<>(queueCapacity),
                threadFactory, rejectedExecutionHandler);
        return threadPoolExecutor;
    }

@Bean
    public Executor myThreadPoolTaskExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new MyThreadPoolTaskExecutor();

        threadPoolTaskExecutor.setCorePoolSize(5);
        
        threadPoolTaskExecutor.setMaxPoolSize(5);
      
        threadPoolTaskExecutor.setQueueCapacity(2000);
 threadPoolTaskExecutor.setThreadNamePrefix("myThreadPoolTaskExecutor-->");

        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }
### Spring Boot线程池的配置与使用 #### 自动配置线程池 Spring Boot 提供了 `@EnableAsync` 注解来启用异步方法执行的支持。默认情况下,当启用了该注解时,会创建一个基于 Java 的 `SimpleAsyncTaskExecutor` 来处理所有的异步调用[^1]。 为了更高效地管理和控制并发任务,建议自定义线程池替代默认实现: ```java @Configuration @EnableAsync public class AsyncConfig implements AsyncConfigurer { @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(7); executor.setMaxPoolSize(42); executor.setQueueCapacity(100); executor.initialize(); return executor; } } ``` 这段代码展示了如何通过继承 `AsyncConfigurer` 接口并重写 `getAsyncExecutor()` 方法来自定义线程池设置,包括核心线程数、最大线程数以及队列容量等重要属性[^3]。 #### 使用自定义线程池执行异步任务 一旦完成了上述配置,在业务逻辑层可以通过简单地标记某个方法为 `async` 关键字的方式将其变为异步运行的方法: ```java @Service public class MyService { @Async public CompletableFuture<Void> performTask(Long id) throws InterruptedException { System.out.println("Processing task " + id +" on thread "+Thread.currentThread().getName()); Thread.sleep(id * 100); // Simulate work being done. return CompletableFuture.completedFuture(null); } } ``` 这里展示了一个服务类中的异步方法例子,它接受一个长时间运行的任务模拟,并返回一个 `CompletableFuture` 对象以便后续链式调用或其他组合操作[^2]。 #### 监控和管理线程池 除了基本的功能外,还可以借助 Actuator 和 Micrometer 等工具对线程池的状态进行监控,比如当前活动线程数量、已完成任务总数等指标。这有助于及时发现潜在瓶颈并对性能做出相应调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值