📚 分类
线程池
🕵🏽‍♀️ 问题描述
线程池的种类有哪些?
👨‍🏫 问题讲解
1. FixedThreadPool:固定数量的线程池,当任务提交时,线程池会启动一个新线程执行任务,直到达到最大线程数。

public static ExecutorService newFixedThreadPool(int nThreads){
  return new ThreadPoolExecutor(
    nThreads,
    nThreads.
    0L,
    TimeUnit.MILLISECONDS.
    new LinkedBlockingQueue());
  )
}

✔ 核心线程数与最大线程数一样,
✔ 没有救急线程
✔ 阻塞队列是LinkedBlockingQueue,最大容量为Integer.MAX_VALUE
✔ 适用于任务量已知,相对耗时的任务

2. CachedThreadPool:可缓存的线程池,当任务提交时,如果线程池中没有空闲线程,则会创建一个新线程执行任务;如果线程池已达到最大线程数,则会将任务放入队列中等待执行。

public static ExecutorService newCachedThreadPool(){
  return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue());
}

✔ 核心线程数为0
✔ 最大线程数是Integer.MAX VALUE
✔ 阻塞队列为SynchronousQueue:不存储元素的阻塞队列,每个插入操作都必须等待一个移出操作。
✔ 适合任务数比较密集,但每个任务执行时间较短的情况

3. SingleThreadPool:单线程化的线程池,只允许一个线程在执行任务,其他任务需要等待。

public static ExecutorService newSingleThreadExecutar(
 return new FinalizableDelegatedExecutorService(
  new ThreadPoolExecutor(
    1, 
    1, 
    0L, 
    TimeUnit.MILLISECONDS, 
    new LinkedBlockingQueue())
  );
}

✔ 核心线程数与最大线程数一样,都是1
✔ 没有救急线程
✔ 阻塞队列是LinkedBlockingQueue,最大容量为Integer.MAX_VALUE
✔ 适用于按照顺序执行的任务

4. ScheduledThreadPool:定时执行的线程池,可以在指定的延迟后执行任务或者定期执行任务。

public ScheduledThreadPoolExecutor(int corePoolSize){
    super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS, new DelayedWorkQueue());
}

✔ 核心线程数可指定
✔ 救急线程,Integer.MAX_VALUE
✔ 阻塞队列是DelayedWorkQueue
✔ 适用于延时胡总或周期执行的任务
🏳️‍🌈 问题总结
❒ newFixedThreadPool: 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
❒ newSingleThreadExecutor: 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO)执行。
❒ newCachedThreadPool: 创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
❒ newScheduledThreadPool: 可以执行延迟任务的线程池,支持定时及周期性任务执行。
📖 问题信息
📈 浏览次数:17 | 📅 更新时间:2025-12-14 11:47:03
📦 创建信息
🏷️ ID:119 | 📅 创建时间:2025-01-07 12:33:00