Java线程池

本文详细介绍了Java中三种常见的线程池实现:FixedThreadPool、CachedThreadPool 和 SingleThreadPool 的使用方法及应用场景,通过示例代码展示了不同线程池的特点。

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

Java线程池(ExecutorService)使用

一、前提

/**
 * 线程运行demo,运行时打出线程id以及传入线程中参数
 */
public class ThreadRunner implements Runnable {

    private final SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss.SSS");

    /**
     * 线程私有属性,创建线程时创建
     */
    private Integer num;

    public ThreadRunner(Integer num) {
        this.num = num;
    }

    @Override
    public void run() {
        System.out.println("thread:" + Thread.currentThread().getName() + ",time:" + format.format(new Date()) + ",num:" + num);
        try {//使线程睡眠,模拟线程阻塞情况
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
  • 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

二、分类

1、FixedThreadPool-有一个固定大小的线程池

public class FixedThreadPoolDemo {

    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(4);
        for(int i = 0 ; i < 50 ; i++){
            pool.submit(new ThreadRunner((i + 1)));
        }
        pool.shutdown();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

输出:

thread:pool-1-thread-2,time:16:14:45.677,num:2
thread:pool-1-thread-4,time:16:14:45.678,num:4
thread:pool-1-thread-3,time:16:14:45.680,num:3
thread:pool-1-thread-1,time:16:14:45.684,num:1
thread:pool-1-thread-4,time:16:14:46.680,num:5
thread:pool-1-thread-2,time:16:14:46.680,num:6
thread:pool-1-thread-3,time:16:14:46.680,num:7
thread:pool-1-thread-1,time:16:14:46.684,num:8
thread:pool-1-thread-4,time:16:14:47.680,num:9
thread:pool-1-thread-2,time:16:14:47.680,num:10
thread:pool-1-thread-3,time:16:14:47.681,num:11
thread:pool-1-thread-1,time:16:14:47.684,num:12
thread:pool-1-thread-4,time:16:14:48.681,num:13
thread:pool-1-thread-2,time:16:14:48.681,num:14
thread:pool-1-thread-3,time:16:14:48.681,num:15
thread:pool-1-thread-1,time:16:14:48.684,num:16
thread:pool-1-thread-4,time:16:14:49.681,num:17
thread:pool-1-thread-2,time:16:14:49.682,num:18
thread:pool-1-thread-3,time:16:14:49.682,num:19
thread:pool-1-thread-1,time:16:14:49.684,num:20
thread:pool-1-thread-4,time:16:14:50.681,num:21
thread:pool-1-thread-2,time:16:14:50.682,num:22
thread:pool-1-thread-3,time:16:14:50.682,num:23
thread:pool-1-thread-1,time:16:14:50.684,num:24
thread:pool-1-thread-4,time:16:14:51.681,num:25
thread:pool-1-thread-2,time:16:14:51.682,num:26
thread:pool-1-thread-3,time:16:14:51.682,num:27
thread:pool-1-thread-1,time:16:14:51.684,num:28
thread:pool-1-thread-4,time:16:14:52.681,num:29
thread:pool-1-thread-2,time:16:14:52.682,num:30
thread:pool-1-thread-3,time:16:14:52.682,num:31
thread:pool-1-thread-1,time:16:14:52.684,num:32
thread:pool-1-thread-4,time:16:14:53.681,num:33
thread:pool-1-thread-2,time:16:14:53.682,num:34
thread:pool-1-thread-3,time:16:14:53.683,num:35
thread:pool-1-thread-1,time:16:14:53.685,num:36
thread:pool-1-thread-2,time:16:14:54.682,num:38
thread:pool-1-thread-4,time:16:14:54.682,num:37
thread:pool-1-thread-3,time:16:14:54.683,num:39
thread:pool-1-thread-1,time:16:14:54.686,num:40
thread:pool-1-thread-2,time:16:14:55.682,num:41
thread:pool-1-thread-4,time:16:14:55.682,num:42
thread:pool-1-thread-3,time:16:14:55.683,num:43
thread:pool-1-thread-1,time:16:14:55.686,num:44
thread:pool-1-thread-2,time:16:14:56.682,num:45
thread:pool-1-thread-4,time:16:14:56.683,num:46
thread:pool-1-thread-3,time:16:14:56.684,num:47
thread:pool-1-thread-1,time:16:14:56.686,num:48
thread:pool-1-thread-2,time:16:14:57.683,num:49
thread:pool-1-thread-4,time:16:14:57.683,num:50
  • 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
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50

总结: 
- 池中线程数量固定,不会发生变化 
- 使用无界的LinkedBlockingQueue,要综合考虑生成与消费能力,生成过剩,可能导致堆内存溢出。 
- 适用一些很稳定很固定的正规并发线程,多用于服务器

2、CachedThreadPool

public class CachedThreadPoolDemo {

    public static void main(String[] args) {
        ExecutorService pool = Executors.newCachedThreadPool();
        for(int i = 0 ; i < 50 ; i++){
            pool.submit(new ThreadRunner((i + 1)));
        }
        pool.shutdown();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

输出:

thread:pool-1-thread-2,time:16:17:21.289,num:2
thread:pool-1-thread-3,time:16:17:21.290,num:3
thread:pool-1-thread-4,time:16:17:21.290,num:4
thread:pool-1-thread-6,time:16:17:21.291,num:6
thread:pool-1-thread-7,time:16:17:21.291,num:7
thread:pool-1-thread-8,time:16:17:21.291,num:8
thread:pool-1-thread-1,time:16:17:21.292,num:1
thread:pool-1-thread-10,time:16:17:21.293,num:10
thread:pool-1-thread-5,time:16:17:21.294,num:5
thread:pool-1-thread-11,time:16:17:21.294,num:11
thread:pool-1-thread-15,time:16:17:21.294,num:15
thread:pool-1-thread-9,time:16:17:21.294,num:9
thread:pool-1-thread-16,time:16:17:21.295,num:16
thread:pool-1-thread-20,time:16:17:21.295,num:20
thread:pool-1-thread-14,time:16:17:21.296,num:14
thread:pool-1-thread-12,time:16:17:21.296,num:12
thread:pool-1-thread-19,time:16:17:21.297,num:19
thread:pool-1-thread-13,time:16:17:21.299,num:13
thread:pool-1-thread-17,time:16:17:21.300,num:17
thread:pool-1-thread-18,time:16:17:21.302,num:18
thread:pool-1-thread-22,time:16:17:21.304,num:22
thread:pool-1-thread-23,time:16:17:21.304,num:23
thread:pool-1-thread-24,time:16:17:21.305,num:24
thread:pool-1-thread-21,time:16:17:21.305,num:21
thread:pool-1-thread-26,time:16:17:21.305,num:26
thread:pool-1-thread-25,time:16:17:21.306,num:25
thread:pool-1-thread-29,time:16:17:21.307,num:29
thread:pool-1-thread-28,time:16:17:21.308,num:28
thread:pool-1-thread-30,time:16:17:21.308,num:30
thread:pool-1-thread-34,time:16:17:21.308,num:34
thread:pool-1-thread-35,time:16:17:21.308,num:35
thread:pool-1-thread-33,time:16:17:21.308,num:33
thread:pool-1-thread-27,time:16:17:21.309,num:27
thread:pool-1-thread-32,time:16:17:21.308,num:32
thread:pool-1-thread-31,time:16:17:21.309,num:31
thread:pool-1-thread-36,time:16:17:21.310,num:36
thread:pool-1-thread-37,time:16:17:21.310,num:37
thread:pool-1-thread-38,time:16:17:21.310,num:38
thread:pool-1-thread-42,time:16:17:21.310,num:42
thread:pool-1-thread-40,time:16:17:21.310,num:40
thread:pool-1-thread-41,time:16:17:21.311,num:41
thread:pool-1-thread-47,time:16:17:21.762,num:47
thread:pool-1-thread-43,time:16:17:21.762,num:43
thread:pool-1-thread-39,time:16:17:21.762,num:39
thread:pool-1-thread-45,time:16:17:21.762,num:45
thread:pool-1-thread-44,time:16:17:21.763,num:44
thread:pool-1-thread-46,time:16:17:21.761,num:46
thread:pool-1-thread-48,time:16:17:21.761,num:48
thread:pool-1-thread-49,time:16:17:21.765,num:49
thread:pool-1-thread-50,time:16:17:21.765,num:50
  • 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
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50

总结 
- 池中线程时随着处理数据增加而增加 
- 线程数并不是一直增加,如果有新任务需要执行时,首先查询池中是否有空闲线程并且还为到空闲截止时间,如果有,则使用空闲线程,如果没有,则创建新线程并放入池中。 
- 用于执行一些生存期很短的异步型任务。不适用于IO等长延时操作,因为这可能会创建大量线程,导致系统崩溃。 
- 使用SynchronousQueue作为阻塞队列,如果有新任务进入队列,必须队列中数据被其他线程处理,否则会等待。

3、SingleThreadExecutor

public class SingleThreadPoolDemo {

    public static void main(String[] args) {
        ExecutorService pool = Executors.newSingleThreadExecutor();
        for(int i = 0 ; i < 50 ; i++){
            pool.submit(new ThreadRunner((i + 1)));
        }
        pool.shutdown();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

输出:

thread:pool-1-thread-1,time:16:20:10.194,num:1
thread:pool-1-thread-1,time:16:20:11.197,num:2
thread:pool-1-thread-1,time:16:20:12.197,num:3
thread:pool-1-thread-1,time:16:20:13.197,num:4
thread:pool-1-thread-1,time:16:20:14.197,num:5
thread:pool-1-thread-1,time:16:20:15.198,num:6
thread:pool-1-thread-1,time:16:20:16.198,num:7
thread:pool-1-thread-1,time:16:20:17.198,num:8
thread:pool-1-thread-1,time:16:20:18.198,num:9
thread:pool-1-thread-1,time:16:20:19.198,num:10
thread:pool-1-thread-1,time:16:20:20.198,num:11
thread:pool-1-thread-1,time:16:20:21.199,num:12
thread:pool-1-thread-1,time:16:20:22.200,num:13
thread:pool-1-thread-1,time:16:20:23.200,num:14
thread:pool-1-thread-1,time:16:20:24.200,num:15
thread:pool-1-thread-1,time:16:20:25.200,num:16
thread:pool-1-thread-1,time:16:20:26.201,num:17
thread:pool-1-thread-1,time:16:20:27.201,num:18
thread:pool-1-thread-1,time:16:20:28.201,num:19
thread:pool-1-thread-1,time:16:20:29.201,num:20
thread:pool-1-thread-1,time:16:20:30.202,num:21
thread:pool-1-thread-1,time:16:20:31.202,num:22
thread:pool-1-thread-1,time:16:20:32.203,num:23
thread:pool-1-thread-1,time:16:20:33.203,num:24
thread:pool-1-thread-1,time:16:20:34.203,num:25
thread:pool-1-thread-1,time:16:20:35.203,num:26
thread:pool-1-thread-1,time:16:20:36.203,num:27
thread:pool-1-thread-1,time:16:20:37.203,num:28
thread:pool-1-thread-1,time:16:20:38.203,num:29
thread:pool-1-thread-1,time:16:20:39.203,num:30
thread:pool-1-thread-1,time:16:20:40.203,num:31
thread:pool-1-thread-1,time:16:20:41.203,num:32
thread:pool-1-thread-1,time:16:20:42.203,num:33
thread:pool-1-thread-1,time:16:20:43.204,num:34
thread:pool-1-thread-1,time:16:20:44.204,num:35
thread:pool-1-thread-1,time:16:20:45.204,num:36
thread:pool-1-thread-1,time:16:20:46.204,num:37
thread:pool-1-thread-1,time:16:20:47.205,num:38
thread:pool-1-thread-1,time:16:20:48.205,num:39
thread:pool-1-thread-1,time:16:20:49.205,num:40
thread:pool-1-thread-1,time:16:20:50.206,num:41
thread:pool-1-thread-1,time:16:20:51.206,num:42
thread:pool-1-thread-1,time:16:20:52.207,num:43
thread:pool-1-thread-1,time:16:20:53.207,num:44
thread:pool-1-thread-1,time:16:20:54.207,num:45
thread:pool-1-thread-1,time:16:20:55.207,num:46
thread:pool-1-thread-1,time:16:20:56.207,num:47
thread:pool-1-thread-1,time:16:20:57.208,num:48
thread:pool-1-thread-1,time:16:20:58.208,num:49
thread:pool-1-thread-1,time:16:20:59.209,num:50
  • 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
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50

总结: 
- 线程中只有一个线程在执行 
- 适用于有明确执行顺序但是不影响主线程的任务,压入池中的任务会按照队列顺序执行。 
- 使用无界的LinkedBlockingQueue,要综合考虑生成与消费能力,生成过剩,可能导致堆内存溢出。

三、源码

public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
  • 1
  • 2
  • 3
  • 4
public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
  • 1
  • 2
  • 3
  • 4
 public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

* ThreadPoolExecutor 构造方法*

public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue) {
    this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
         Executors.defaultThreadFactory(), defaultHandler);
}


 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;
}
  • 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
  • corePoolSize:线程池核心线程数量 
    1. 如果池中线程数量少于核心线程池数量,则直接新建线程处理当前任务。
    2. 核心线程池空闲不会被回收。
    3. 当池中无空闲线程时,新任务将被添加到阻塞队列
  • maximumPoolSize:线程池最大线程数量 
    1. 当阻塞队列已满,并且有新任务还在入队时,创建新的线程处理,直到线程数大于maximumPoolSize。
    2. 超出corePoolSize部分的线程超过空闲时间后会被回收
    3. 当线程已经超出corePoolSize,并且队列容量已满,则拒绝入队。
  • keepAliveTime unit:线程存活时间 
    1. 当线程超出corePoolSize时生效
    2. 线程空余keepAliveTime后,将被回收
  • workQueue:线程使用阻塞队列
  • threadFactory:创建线程池工厂 
    1. 用于控制创建线程或者销毁线程时加入其它逻辑
  • handler:线程池拒绝策略 
    1. 直接丢弃(DiscardPolicy)
    2. 丢弃队列中最老的任务(DiscardOldestPolicy)。
    3. 抛异常(AbortPolicy)
    4. 将任务分给调用线程来执行(CallerRunsPolicy)
版权声明:知识是公共的,有建议大家一起讨论 https://blog.youkuaiyun.com/wanghao_0206/article/details/76460877
<think>我们正在讨论Java线程池的使用和原理。根据引用内容,线程池Java中主要通过ThreadPoolExecutor类实现,从JDK5开始内置支持。线程池的好处包括重用线程、控制并发数量、管理线程生命周期等。常见的线程池类型有:FixedThreadPool(固定容量)、CachedThreadPool(缓存)、SingleThreadExecutor(单线程)、ScheduledThreadPool(定时任务)以及通过ThreadPoolExecutor自定义创建。我们将分步骤讲解:1.线程池的核心原理2.创建线程池的五种方式(包括不推荐的原因)3.重点讲解ThreadPoolExecutor及其参数4.线程池的工作机制(任务提交、执行、拒绝策略等)5.使用示例注意:根据引用[3]和[4],ThreadPoolExecutor是构建线程池的核心类,因此我们将重点分析。步骤1线程池的核心原理线程池通过预先创建一定数量的线程并维护它们,避免频繁创建和销毁线程的开销。当有任务提交时,线程池分配空闲线程执行任务;若没有空闲线程,任务将被放入队列等待;当队列满时,根据设定的拒绝策略处理。步骤2:创建线程池的五种方式(引用[3]和[5])1.newCachedThreadPool:创建一个可缓存的线程池,线程数可无限增加(最大为Integer.MAX_VALUE),空闲线程默认60秒回收。不推荐原因:可能创建过多线程导致OOM。2.newFixedThreadPool:固定大小的线程池,使用无界队列(LinkedBlockingQueue)。不推荐原因:无界队列可能堆积大量任务导致OOM。3.newSingleThreadExecutor:只有一个线程的线程池,同样使用无界队列。不推荐原因同上。4.newScheduledThreadPool:用于定时或周期性任务的线程池。不推荐直接使用的原因是其最大线程数为Integer.MAX_VALUE,可能创建过多线程。5.推荐方式:直接使用ThreadPoolExecutor构造函数创建,可明确指定参数,避免资源耗尽。步骤3:ThreadPoolExecutor的七个参数(引用[3]和[4])构造方法如下:```javapublicThreadPoolExecutor(intcorePoolSize,intmaximumPoolSize,longkeepAliveTime,TimeUnitunit,BlockingQueue<Runnable>workQueue,ThreadFactorythreadFactory,RejectedExecutionHandlerhandler)```1.corePoolSize:核心线程数,即使空闲也不会被回收(除非设置allowCoreThreadTimeOut)2.maximumPoolSize:最大线程数3.keepAliveTime:非核心线程的空闲存活时间4.unit:存活时间单位5.workQueue:任务队列(常用有ArrayBlockingQueue有界队列,LinkedBlockingQueue无界队列,SynchronousQueue同步移交队列)6.threadFactory:线程工厂,用于创建线程7.handler:拒绝策略(当线程池和队列都满时触发)步骤4:线程池的工作机制(任务提交执行流程)1.提交任务后,如果当前线程数小于corePoolSize,则创建新线程执行(即使有空闲线程)。2.如果当前线程数>=corePoolSize,则将任务放入workQueue。3.如果队列已满,且线程数小于maximumPoolSize,则创建新的非核心线程执行。4.如果队列已满且线程数达到maximumPoolSize,则触发拒绝策略。拒绝策略(handler)有四种:-AbortPolicy(默认):抛出RejectedExecutionException-CallerRunsPolicy:由调用线程执行该任务-DiscardPolicy:丢弃任务,不抛异常-DiscardOldestPolicy:丢弃队列最前面的任务,然后重试步骤5:使用示例(以ThreadPoolExecutor为例)下面是一个自定义线程池的示例:```javaimportjava.util.concurrent.*;publicclassThreadPoolExample{publicstaticvoidmain(String[]args){//创建线程池ThreadPoolExecutorexecutor=newThreadPoolExecutor(2,//核心线程数5,//最大线程数60,//空闲线程存活时间TimeUnit.SECONDS,newArrayBlockingQueue<>(10),//有界队列,容量10Executors.defaultThreadFactory(),newThreadPoolExecutor.AbortPolicy());//拒绝策略:直接抛出异常//提交任务for(inti=0;i<15;i++){finalinttaskId=i;executor.execute(()->{System.out.println("Task"+taskId+"isrunningonthread"+Thread.currentThread().getName());try{Thread.sleep(1000);//模拟任务执行}catch(InterruptedExceptione){e.printStackTrace();}});}//关闭线程池executor.shutdown();}}```注意:实际任务数15个,核心线程2个,最大线程5个,队列容量10个。因此前2个任务会创建核心线程执行,接下来的10个任务放入队列,然后第13、14、15个任务会创建非核心线程(共3个非核心线程,总线程数5个)。如果超过15个任务(比如16个),则会触发拒绝策略。最后,关于线程池的关闭,可以使用shutdown()(等待已提交任务完成)或shutdownNow()(尝试中断所有线程,停止任务)。总结:使用线程池时,推荐直接使用ThreadPoolExecutor构造函数,根据实际需求设置参数,避免使用Executors工厂方法可能导致的资源耗尽问题。相关问题:1.线程池中任务队列有哪些类型?各自特点是什么?2.如何合理设置线程池的核心线程数和最大线程数?3.线程池的拒绝策略有哪些?如何自定义拒绝策略?4.如何监控线程池的运行状态?5.线程池中线程是如何创建的?如何自定义线程工厂?</think>### Java线程池使用指南与原理分析 Java线程池通过`java.util.concurrent`包实现,核心类是`ThreadPoolExecutor`。线程池的核心思想是**复用线程**,避免频繁创建销毁线程的开销。线程池中的线程执行完任务后不会销毁,而是回到池中等待新任务[^2]。 --- #### **一、线程池的创建方式** Java提供5种创建线程池的方法(实际都是`ThreadPoolExecutor`的包装): 1. **固定大小线程池**(推荐) ```java ExecutorService fixedPool = Executors.newFixedThreadPool(5); // 固定5个线程 ``` - 特点:核心线程数=最大线程数,使用无界队列`LinkedBlockingQueue` - 风险:任务过多时可能导致OOM(队列无限增长)[^5] 2. **缓存线程池**(不推荐) ```java ExecutorService cachedPool = Executors.newCachedThreadPool(); ``` - 特点:线程数无上限(`Integer.MAX_VALUE`),空闲线程60秒回收 - 风险:高并发时可能创建大量线程导致OOM[^3] 3. **单线程池** ```java ExecutorService singlePool = Executors.newSingleThreadExecutor(); ``` - 特点:仅1个线程,保证任务顺序执行 - 风险:同固定线程池(无界队列问题) 4. **定时任务线程池** ```java ScheduledExecutorService scheduledPool = Executors.newScheduledThreadPool(3); ``` 5. **推荐做法:手动创建`ThreadPoolExecutor`** ```java ThreadPoolExecutor customPool = new ThreadPoolExecutor( 4, // 核心线程数 10, // 最大线程数 60, // 空闲线程存活时间(秒) TimeUnit.SECONDS, new ArrayBlockingQueue<>(100), // 有界队列(容量100) new ThreadPoolExecutor.AbortPolicy() // 拒绝策略 ); ``` --- #### **二、核心参数详解(7个关键参数)** ```java public ThreadPoolExecutor( int corePoolSize, // 核心线程数(常驻线程) int maximumPoolSize, // 最大线程数 long keepAliveTime, // 非核心线程空闲存活时间 TimeUnit unit, // 时间单位 BlockingQueue<Runnable> workQueue, // 任务队列 ThreadFactory threadFactory, // 线程工厂 RejectedExecutionHandler handler // 拒绝策略 ) ``` 1. **任务队列类型** - `ArrayBlockingQueue`:**有界队列**(推荐),避免OOM - `LinkedBlockingQueue`:**无界队列**(默认) - `SynchronousQueue`:不存储任务,直接移交线程 2. **拒绝策略**(当队列和线程池全满时触发) - `AbortPolicy`(默认):抛出`RejectedExecutionException` - `CallerRunsPolicy`:由调用者线程直接执行任务 - `DiscardPolicy`:静默丢弃任务 - `DiscardOldestPolicy`:丢弃队列最旧的任务 --- #### **三、线程池工作原理** 1. **任务提交流程**: - 当线程数 < `corePoolSize`,**创建新线程**执行任务 - 当线程数 >= `corePoolSize`,任务进入**工作队列** - 当队列已满且线程数 < `maximumPoolSize`,**创建临时线程**执行 - 当队列满且线程数达到`maximumPoolSize`,触发**拒绝策略**[^4] 2. **线程回收机制**: - 核心线程默认不回收(除非设置`allowCoreThreadTimeOut(true)`) - 非核心线程空闲超过`keepAliveTime`后自动销毁 --- #### **四、最佳实践** 1. **参数设置建议**: - CPU密集型任务:核心线程数 = CPU核数 + 1 - IO密集型任务:核心线程数 = 2 * CPU核数 - 使用**有界队列**防止资源耗尽 - 拒绝策略选择`CallerRunsPolicy`保证任务不丢失 2. **代码示例**: ```java ThreadPoolExecutor executor = new ThreadPoolExecutor( Runtime.getRuntime().availableProcessors(), // 核心线程数=CPU核数 Runtime.getRuntime().availableProcessors() * 2, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<>(500), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy() ); // 提交任务 executor.execute(() -> System.out.println("Task running")); // 优雅关闭 executor.shutdown(); executor.awaitTermination(1, TimeUnit.MINUTES); ``` 3. **注意事项**: - 避免使用`Executors`快捷方法(有OOM风险) - 监控线程池状态(通过`getActiveCount()`等方法) - 务必调用`shutdown()`释放资源 --- #### **五、原理解析** - **线程复用**:通过`Worker`类封装线程,循环从队列获取任务执行[^3] - **任务调度**:核心逻辑在`ThreadPoolExecutor.execute()`方法中 - **资源控制**:通过`BlockingQueue`实现生产者-消费者模型 > 线程池的本质是**资源池化技术**(Pooling),通过复用线程降低系统开销,同时提供流量缓冲和容错能力[^4]。 --- ### 相关问题 1. **为什么`FixedThreadPool`使用无界队列会导致OOM?如何避免?** 2. **线程池中`corePoolSize`和`maximumPoolSize`设置不当会产生什么后果?** 3. **如何实现一个自定义拒绝策略(如记录日志或降级处理)?** 4. **线程池的`shutdown()`和`shutdownNow()`有什么区别?** 5. **如何监控线程池的运行状态(如队列积压、活跃线程数)?** [^1]: ThreadPoolExecutor是Java线程池的核心实现类。 [^2]: JDK5开始内置线程池,线程执行后返回池中复用。 [^3]: 手动创建ThreadPoolExecutor可避免资源耗尽风险。 [^4]: 线程池通过队列缓冲和动态扩缩容管理任务。 [^5]: FixedThreadPool的无界队列可能导致OOM。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值