Java线程池参数详解

发布时间:2023-05-18

一、核心参数

  1. corePoolSize 核心池的大小,即线程池维护线程的最少数量。当提交一个任务到线程池时,线程池会创建一个线程来执行任务,即使其他线程处于空闲状态。如果池中的线程数达到 corePoolSize 后,新提交的任务将被放入队列中等待。如果队列已满,且池中的线程数小于 maximumPoolSize,则创建新的线程执行任务。如果池中的线程数达到 maximumPoolSize,则根据设置的拒绝策略来处理任务。
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
    
  2. maximumPoolSize 线程池最大数量。当线程池中的线程数目达到这个数目时,新的任务会被放入队列中等待。如果队列满了,调用者就必须自己处理这个任务。如果使用无界的任务队列这个参数就没有任何作用。
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
    
  3. keepAliveTime 线程池中工作线程空闲后,保持存活的时间。
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
    

二、任务队列参数

  1. workQueue 任务队列,用来存储等待执行的任务。常用的有四种队列:
    // 线程池中任务队列为SynchronousQueue
    ThreadPoolExecutor threadPoolExecutor1 = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime,
                TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
    // 线程池中任务队列为LinkedBlockingQueue
    ThreadPoolExecutor threadPoolExecutor2 = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime,
                TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
    // 线程池中任务队列为ArrayBlockingQueue
    ThreadPoolExecutor threadPoolExecutor3 = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime,
                TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(100));
    // 线程池中任务队列为PriorityBlockingQueue
    ThreadPoolExecutor threadPoolExecutor4 = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime,
                TimeUnit.SECONDS, new PriorityBlockingQueue<Runnable>());
    
  2. capacity 任务队列的容量。如果任务数量达到这个值,新提交的任务将会被拒绝,并根据设置的拒绝策略来处理任务。
    // 容量为100的有界队列
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime,
                TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(100));
    

三、超时策略参数

  1. allowCoreThreadTimeOut 该属性为 true 时,表示允许为核心线程设置超时时间,即当线程数大于核心线程数时,核心线程也会参与超时检查。
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
    threadPoolExecutor.allowCoreThreadTimeOut(true);
    
  2. rejectedExecutionHandler 当线程池中的资源已经全部使用,添加新线程被拒绝时,会进行拒绝处理。常用的拒绝策略有四种:
    // 拒绝策略为AbortPolicy
    ThreadPoolExecutor threadPoolExecutor1 = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime,
                TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadPoolExecutor.AbortPolicy());
    // 拒绝策略为DiscardPolicy
    ThreadPoolExecutor threadPoolExecutor2 = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime,
                TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadPoolExecutor.DiscardPolicy());
    // 拒绝策略为DiscardOldestPolicy
    ThreadPoolExecutor threadPoolExecutor3 = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime,
                TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadPoolExecutor.DiscardOldestPolicy());
    // 拒绝策略为CallerRunsPolicy
    ThreadPoolExecutor threadPoolExecutor4 = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime,
                TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadPoolExecutor.CallerRunsPolicy());
    

四、线程池扩展参数

  1. ThreadFactory 通过 ThreadFactory 方式自定义线程池中的线程对象,可以自定义线程的名字、是否为守护线程等。
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
       private final AtomicInteger atomicInteger = new AtomicInteger(0);
       public Thread newThread(Runnable r) {
           Thread thread = new Thread(r);
           thread.setName("Thread-" + atomicInteger.getAndIncrement());
           return thread;
       }
    });
    
  2. beforeExecute 和 afterExecute 在每个任务之前和之后执行的操作。可以用来统计任务的执行时间等。
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadPoolExecutor.AbortPolicy());
    threadPoolExecutor.setThreadFactory(new ThreadFactory() {
       private final AtomicInteger atomicInteger = new AtomicInteger(0);
       public Thread newThread(Runnable r) {
           Thread thread = new Thread(r);
           thread.setName("Thread-" + atomicInteger.getAndIncrement());
           return thread;
       }
    });
    // 执行任务前处理
    threadPoolExecutor.prestartAllCoreThreads();
    threadPoolExecutor.execute(() -> {
        // 任务执行时间统计
        long startTime = System.currentTimeMillis();
        try {
            // 执行任务
        } finally {
            // 任务执行时间统计
            long endTime = System.currentTimeMillis();
            log.info("任务执行时间: " + (endTime - startTime) + " ms");
        }
    });
    

五、总结

本文主要对 Java 线程池中的主要参数进行了详细的阐述,包括核心参数、任务队列参数、超时策略参数以及线程池扩展参数。在使用线程池时,需要根据具体业务场景选择合适的参数配置,避免线程池资源浪费或者任务无法及时执行的情况。