Executors 工厂方法有哪些
java 中 java.util.concurrent.executors 类提供了五个常用的静态工厂方法来创建线程池,分别是 newfixedthreadpool、newcachedthreadpool、newsinglethreadexecutor、newscheduledthreadpool 和 newworkstealingpool。这些方法通过预设的参数组合,快速生成不同特性的 threadpoolexecutor 实例,开发者只需根据业务场景选择合适的方法即可。

固定大小与单线程池的对比
newFixedThreadPool 和 newSingleThreadExecutor 的核心区别在于工作线程的数量限制。前者允许指定数量的线程并发执行任务,后者则严格保证同一时刻只有一个线程运行。两者都使用无界的 LinkedBlockingQueue 来存储等待任务,因此在高负载下可能导致内存溢出风险。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class FixedVsSingle {
public static void main(String[] args) {
// 创建固定大小为3的线程池
ExecutorService fixedPool = Executors.newFixedThreadPool(3);
// 创建单线程池
ExecutorService singlePool = Executors.newSingleThreadExecutor();
System.out.println("Fixed Pool Type: " + fixedPool.getClass().getSimpleName());
System.out.println("Single Pool Type: " + singlePool.getClass().getSimpleName());
fixedPool.shutdown();
singlePool.shutdown();
}
}缓存线程池与定时线程池的特性
newCachedThreadPool 会根据需要创建新线程,空闲线程保留60秒后回收,适合执行大量短期异步任务。而 newScheduledThreadPool 支持延迟执行和周期性执行任务,底层基于 DelayedWorkQueue。这两个方法分别适用于不同的时间敏感型场景,且同样存在队列无界带来的潜在风险。
你是 TypeScript 项目架构专家,专注于脚手架搭建生产就绪的 Node.js 和前端应用。生成包含现代工具链(pnpm、Vite、Next.js)、类型
立即学习“Java免费学习笔记(深入)”;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class CachedVsScheduled {
public static void main(String[] args) {
// 创建缓存线程池
ScheduledExecutorService cachedPool = (ScheduledExecutorService) Executors.newCachedThreadPool();
// 创建定时线程池,核心线程数为5
ScheduledExecutorService scheduledPool = Executors.newScheduledThreadPool(5);
System.out.println("Cached Pool Class: " + cachedPool.getClass().getSimpleName());
System.out.println("Scheduled Pool Class: " + scheduledPool.getClass().getSimpleName());
cachedPool.shutdown();
scheduledPool.shutdown();
}
}基于 newFixedThreadPool 输入条件的具体行为
当调用 Executors.newFixedThreadPool(nThreads) 时,如果传入的 nThreads 参数为负数或零,程序会抛出 IllegalArgumentException。这是该方法的一个明确输入条件检查,确保线程池至少拥有一个工作线程。在实际开发中,必须对输入参数进行校验,以避免运行时异常。

















