# Springboot中自定义线程池大小

作者:Odboy (opens new window)

本站地址:https://blog.odboy.cn (opens new window)

# 示例

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.*;

@Configuration
public class ThreadPoolConfig {

  @Bean
  public ExecutorService threadPool() {
    int corePoolSize = 5; // 核心线程数
    int maximumPoolSize = 10; // 最大线程数
    long keepAliveTime = 60L; // 空闲线程存活时间(秒)
    TimeUnit unit = TimeUnit.SECONDS; // 时间单位
    BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(100); // 工作队列大小

    ThreadFactory threadFactory = runnable -> {
      Thread thread = new Thread(runnable);
      thread.setName("my-thread-pool-" + thread.getId());
      return thread;
    };

    RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy(); // 拒绝策略

    return new ThreadPoolExecutor(
        corePoolSize,
        maximumPoolSize,
        keepAliveTime,
        unit,
        workQueue,
        threadFactory,
        handler
    );
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
最近更新: 2025-08-18
Springboot中自定义线程池大小

2017 - 武林秘籍   |