ThreadPoolExecutor创建线程池启动项目报错问题

本文探讨了如何在Spring Boot项目中使用ThreadPoolExecutor时避免因参数配置不当导致的IllegalArgumentException,重点在于理解corePoolSize和maximumPoolSize的关系,并提供了一种修正方法。

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

  • ThreadPoolExecutor创建线程,如下代码:
ThreadPoolExecutor threadPoolExecutor =
            new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors() + 1, 20, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(100), new ThreadPoolExecutor.CallerRunsPolicy());
  • 启动项目时,报错如下:
Constructor threw exception; nested exception is java.lang.IllegalArgumentException
	at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
	at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1147) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
	... 37 common frames omitted
Caused by: java.lang.IllegalArgumentException: null
	at java.util.concurrent.ThreadPoolExecutor.<init>(ThreadPoolExecutor.java:1314) [na:1.8.0_162]
	at java.util.concurrent.ThreadPoolExecutor.<init>(ThreadPoolExecutor.java:1272) [na:1.8.0_162]
  • 原因分析:corePoolSize必须小于等于maximumPoolSize,而Runtime.getRuntime().availableProcessors() + 1有可能大于20,这时就会抛出IllegalArgumentException,这可以在源码中看到,如下图:
public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }
  • 解决。只需要保证corePoolSize总是<=maximumPoolSize即可,如:
ThreadPoolExecutor threadPoolExecutor =
            new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors() + 1, Runtime.getRuntime().availableProcessors()*2, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(100), new ThreadPoolExecutor.CallerRunsPolicy());
### 使用 `ThreadPoolExecutor` 创建线程池 在 Python 中,`concurrent.futures` 模块提供了 `ThreadPoolExecutor` 类来简化多线程操作。通过该类可以轻松创建并管理线程池,从而实现高效的并发任务处理。 以下是基于所提供的参考资料构建的一个简单示例[^1]: ```python from concurrent.futures import ThreadPoolExecutor, as_completed import time def task(n): """模拟耗时任务""" time.sleep(2) return f"Task {n} completed" # 创建线程池,指定最大工作线程数为3 with ThreadPoolExecutor(max_workers=3) as executor: futures = [] for i in range(5): # 提交5个任务到线程池 future = executor.submit(task, i) futures.append(future) # 获取已完成的任务结果 for future in as_completed(futures): result = future.result() print(result) ``` 上述代码展示了如何利用 `ThreadPoolExecutor` 来提交多个任务,并等待它们完成后再获取其返回值。其中,`max_workers` 参数定义了线程池的最大容量,即最多允许多少个工作线程同时运行[^2]。 #### 关键点解析 - **线程池初始化**: 调用 `ThreadPoolExecutor` 构造函数时可以通过参数 `max_workers` 设置线程数量。 - **任务提交**: 使用 `submit()` 方法向线程池提交可调用对象(如函数),它会立即返回一个代表未来结果的 `Future` 对象。 - **结果收集**: 可以借助 `as_completed()` 函数迭代所有已提交的任务,按实际完成顺序逐一提取结果。 此方式不仅减少了频繁创建和销毁线程带来的开销,还能够更好地控制系统的资源消耗。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值