在 Java 中,ExecutorService 本身不直接提供“并发数”参数,而是通过线程池的实现类来控制并发数量。常见做法如下:
ThreadPoolExecutor 控制并发数(最常用)ThreadPoolExecutor executor = new ThreadPoolExecutor(
corePoolSize, // 核心线程数
maximumPoolSize, // 最大线程数
keepAliveTime,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>()
);
✅ 并发数上限 = maximumPoolSize
corePoolSize:常驻线程数maximumPoolSize:最多同时运行的线程数ExecutorService executor = new ThreadPoolExecutor(
5, 5, 0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>()
);
Executors 工厂方法(简化)ExecutorService executor = Executors.newFixedThreadPool(10);
✅ 并发数 = 10
适用于:
ExecutorService executor = Executors.newSingleThreadExecutor();
如果你的任务是 IO 密集型,可以这样设计:
ExecutorService executor = new ThreadPoolExecutor(
10,
50,
60L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(100)
);
含义:
Semaphore 精确控制并发(进阶)如果你使用的是 CachedThreadPool 或自定义 executor:
Semaphore semaphore = new Semaphore(5);
executor.submit(() -> {
semaphore.acquire();
try {
// 业务逻辑
} finally {
semaphore.release();
}
});
✅ 即使线程池很大,也只会有 5 个任务同时执行
@Bean
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(100);
return executor;
}
| 方式 | 并发数控制点 |
|---|---|
| newFixedThreadPool(n) | n |
| ThreadPoolExecutor | maximumPoolSize |
| Semaphore | permit 数量 |
| Spring ThreadPoolTaskExecutor | maxPoolSize |
如果你有具体场景(如:接口限流、批量任务、IO/CPU 密集),我可以帮你选最合适的配置方案。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。