ThreadPoolExecutor之FixedThreadPool详解

项目中大家基本都使用过线程池,节省线程创建和销毁的成本。Java JDK提供了几种线程池,那么如何选择合适的线程池?这就需要对每一种线程池有较详细的了解,然后根据实际业务类型,选择对应的线程池。 本文主要介绍FixedThreadPool。

定义

    /**
     * Creates a thread pool that reuses a fixed number of threads
     * operating off a shared unbounded queue.  At any point, at most
     * {@code nThreads} threads will be active processing tasks.
     * If additional tasks are submitted when all threads are active,
     * they will wait in the queue until a thread is available.
     * If any thread terminates due to a failure during execution
     * prior to shutdown, a new one will take its place if needed to
     * execute subsequent tasks.  The threads in the pool will exist
     * until it is explicitly {@link ExecutorService#shutdown shutdown}.
     *
     * @param nThreads the number of threads in the pool
     * @return the newly created thread pool
     * @throws IllegalArgumentException if {@code nThreads <= 0}
     */
    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);
    }

简要说明,FixedThreadPool,也就是可重用固定线程数的线程池。 它corePoolSize和 maximumPoolSize是一样的。并且他的keepAliveTime=0, 也就是当线程池中的线程数大于corePoolSize, 多余的空闲线程会被***立即***终止。

它的基本执行过程如下
1, 如果当前运行的线程数少于corePoolSize, 会立刻创建新线程执行任务。
2,当线程数到达corePoolSize后,将任务加入到LinkedBlockingQueue中。
3,当线程执行完任务后,会循环从LinkedBlockingQueue中获取任务来执行。

FixedThreadPool使用了LinkedBlockingQueue, 也就是无界队列(队列最大可容纳Integer.MAX_VALUE), 因此会造成以下影响:
a, 线程池线程数到达corePoolSize后,任务会被存放在LinkedBlockingQueue中
b, 因为无界队列,运行中(未调用shutdown()或者shutdownNow()方法)的不会拒绝任务(队列无界,可以放入"无限"任务)

实际代码

提交到线程池的任务

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

@Slf4j
@Getter
class MyTask implements Runnable {
    private String name;

    public MyTask(String name) {
        this.name = name;
    }
    
    @Override
    public void run() {
        try {
            long threadId = Thread.currentThread().getId();
            Long duration = (long) (Math.random() * 10);
            log.info("Doing a task during : {}, threadId={}" , name , threadId);
            TimeUnit.SECONDS.sleep(duration);
            log.info("done a task during : {}, threadId={}" , name , threadId);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

提交过程

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Slf4j
public class FixedThreadPoolExecutorDemo2 {
    public static void main(String[] args) {
        ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(4);
        for (int i = 0; i < 10; i++) {
            MyTask task = new MyTask("Task " + i);
            if (i == 2) {
                try {
                //这里刻意等待task0和task1完成。
                    TimeUnit.SECONDS.sleep(70);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //线程数
            int activeCount = executor.getActiveCount();
            long taskCount = executor.getTaskCount();
            BlockingQueue queue = executor.getQueue();
            log.info("A new task has been added {}, activeCount={}, taskCount={}, queue={}",
                    task.getName(), activeCount, taskCount, queue.size());
            executor.execute(task);
        }
        System.out.println("Maximum threads inside pool " + executor.getMaximumPoolSize());
        executor.shutdown();
    }
}

分析

重点看日志,从日志我们可以看出它的运行过程与前面的分析一致。

11:47:28.963 [main] INFO com.yq.threadpool.FixedThreadPoolExecutorDemo2 - A new task has been added Task 0, activeCount=0, taskCount=0, queue=0
11:47:28.972 [main] INFO com.yq.threadpool.FixedThreadPoolExecutorDemo2 - A new task has been added Task 1, activeCount=1, taskCount=1, queue=0
11:47:28.973 [pool-1-thread-1] INFO com.yq.threadpool.MyTask - Doing a task during : Task 0, threadId=9
11:47:28.976 [pool-1-thread-2] INFO com.yq.threadpool.MyTask - Doing a task during : Task 1, threadId=10
11:47:31.976 [pool-1-thread-1] INFO com.yq.threadpool.MyTask - done a task during : Task 0, threadId=9
11:47:36.976 [pool-1-thread-2] INFO com.yq.threadpool.MyTask - done a task during : Task 1, threadId=10
11:48:38.972 [main] INFO com.yq.threadpool.FixedThreadPoolExecutorDemo2 - A new task has been added Task 2, activeCount=0, taskCount=2, queue=0
11:48:38.973 [main] INFO com.yq.threadpool.FixedThreadPoolExecutorDemo2 - A new task has been added Task 3, activeCount=1, taskCount=3, queue=0
11:48:38.974 [pool-1-thread-3] INFO com.yq.threadpool.MyTask - Doing a task during : Task 2, threadId=11  (task2 和task3提交时,虽然thread 9和10已经完成了task0和task1,但是线程池为task2生成了thread 11,这是因为线程池设定的线程数是4,现在还没有到达4个线程,所以新提交的任务,就为该任务创建一个线程)
11:48:38.974 [main] INFO com.yq.threadpool.FixedThreadPoolExecutorDemo2 - A new task has been added Task 4, activeCount=2, taskCount=4, queue=0
11:48:38.974 [pool-1-thread-4] INFO com.yq.threadpool.MyTask - Doing a task during : Task 3, threadId=12  (task2 和task3提交时,虽然thread 9和10已经完成了task0和task1,但是线程池位task3生成了thread 12,这是因为线程池设定的线程数是4,现在还没有到达4个线程(现在有3个),所以新提交的任务,就为该任务创建一个线程)
11:48:38.974 [main] INFO com.yq.threadpool.FixedThreadPoolExecutorDemo2 - A new task has been added Task 5, activeCount=2, taskCount=5, queue=1
11:48:38.974 [pool-1-thread-1] INFO com.yq.threadpool.MyTask - Doing a task during : Task 4, threadId=9 (线程总数应达到4个了,新的任务需要等待,然后循环使用以前的线程,这里使用thread 9)
11:48:38.975 [pool-1-thread-1] INFO com.yq.threadpool.MyTask - done a task during : Task 4, threadId=9
11:48:38.975 [main] INFO com.yq.threadpool.FixedThreadPoolExecutorDemo2 - A new task has been added Task 6, activeCount=3, taskCount=6, queue=1
11:48:38.975 [main] INFO com.yq.threadpool.FixedThreadPoolExecutorDemo2 - A new task has been added Task 7, activeCount=3, taskCount=7, queue=1
11:48:38.975 [main] INFO com.yq.threadpool.FixedThreadPoolExecutorDemo2 - A new task has been added Task 8, activeCount=3, taskCount=8, queue=2
11:48:38.975 [main] INFO com.yq.threadpool.FixedThreadPoolExecutorDemo2 - A new task has been added Task 9, activeCount=3, taskCount=9, queue=3
Maximum threads inside pool 4
11:48:38.975 [pool-1-thread-2] INFO com.yq.threadpool.MyTask - Doing a task during : Task 5, threadId=10
11:48:38.976 [pool-1-thread-1] INFO com.yq.threadpool.MyTask - Doing a task during : Task 6, threadId=9
11:48:41.974 [pool-1-thread-3] INFO com.yq.threadpool.MyTask - done a task during : Task 2, threadId=11
11:48:41.974 [pool-1-thread-3] INFO com.yq.threadpool.MyTask - Doing a task during : Task 7, threadId=11
11:48:41.974 [pool-1-thread-3] INFO com.yq.threadpool.MyTask - done a task during : Task 7, threadId=11
11:48:41.974 [pool-1-thread-3] INFO com.yq.threadpool.MyTask - Doing a task during : Task 8, threadId=11
11:48:43.974 [pool-1-thread-3] INFO com.yq.threadpool.MyTask - done a task during : Task 8, threadId=11
11:48:43.974 [pool-1-thread-3] INFO com.yq.threadpool.MyTask - Doing a task during : Task 9, threadId=11
11:48:43.976 [pool-1-thread-2] INFO com.yq.threadpool.MyTask - done a task during : Task 5, threadId=10
11:48:45.974 [pool-1-thread-3] INFO com.yq.threadpool.MyTask - done a task during : Task 9, threadId=11
11:48:45.976 [pool-1-thread-1] INFO com.yq.threadpool.MyTask - done a task during : Task 6, threadId=9
11:48:46.974 [pool-1-thread-4] INFO com.yq.threadpool.MyTask - done a task during : Task 3, threadId=12


Process finished with exit code 0

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
ThreadPoolExecutor 是 Java 提供的用于创建线程池的类,它的构造函数有很多参数,下面是对这些参数的详细解释: 1. corePoolSize:线程池中核心线程的数量。当线程池中的线程数量小于 corePoolSize 时,新的任务会一直创建新的线程直到达到 corePoolSize 个线程。 2. maximumPoolSize:线程池中最大线程数。当线程池中的线程数量达到 corePoolSize 后,新的任务会被放入到等待队列中,等待被执行。如果等待队列已满,且线程池中的线程数量小于 maximumPoolSize,则会创建新的线程执行任务。 3. keepAliveTime:线程池中非核心线程的超时时间。当线程池中的线程数量大于 corePoolSize 时,多余的线程会被回收,但回收前会等待 keepAliveTime 时间,如果在这个时间内没有新的任务需要执行,则这个线程会被终止。 4. TimeUnit:超时时间的单位。 5. workQueue:用于缓存等待执行的任务的队列。ThreadPoolExecutor 提供了多种队列,如 ArrayBlockingQueue、LinkedBlockingQueue、PriorityBlockingQueue 等。可以根据需求选择不同的队列。 6. threadFactory:用于创建新的线程。ThreadPoolExecutor 默认使用 Executors.defaultThreadFactory() 创建线程。如果需要自定义线程创建方式,可以实现 ThreadFactory 接口。 7. handler:线程池中的线程数量达到 maximumPoolSize,并且等待队列已满时,新的任务的处理策略。ThreadPoolExecutor 提供了 4 种策略: - AbortPolicy:直接抛出异常; - CallerRunsPolicy:不在新线程中执行任务,而是让调用 execute 方法的线程执行任务; - DiscardOldestPolicy:丢弃最老的任务,执行当前任务; - DiscardPolicy:直接丢弃任务。 这些参数可以根据实际需求进行调整,以达到最优的线程池效果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值