详聊ThreadPoolExecutor构造器的参数corePoolSize,queueCapacity,maximumPoolSize...

1. 先来看corePoolSize,queueCapacity,maximumPoolSize三者的关系

我猜测很多人都没有理解这三者的关系,包括我,刚开始真的不好理解。后面通过做一些测试慢慢的领悟到了。
好,我们先来看测试用到的代码:
线程池(依赖OwlThreadFactory):

package threadpool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class OwlThreadPoolExecutor {

    /**
     * default value
     */
    private static int corePoolSize = 5;
    private static int maxPoolSize = 10;
    private static int queueCapacity = 100;
    private static Long keepAliveTime = 1L;
    
    public static volatile ThreadPoolExecutor threadPoolExecutorInstance = null;
    
    private OwlThreadPoolExecutor() {}
    
    public static void initialize(int corePoolSite, int maxPoolSite, int queueCapacity, long keepAliveTime) {
        OwlThreadPoolExecutor.corePoolSize = corePoolSite;
        OwlThreadPoolExecutor.maxPoolSize = maxPoolSite;
        OwlThreadPoolExecutor.queueCapacity = queueCapacity;
        OwlThreadPoolExecutor.keepAliveTime = keepAliveTime;
    }
    
    public static ThreadPoolExecutor getThreadPoolExecutorInstance() {
        if (threadPoolExecutorInstance == null || threadPoolExecutorInstance.isShutdown()) {
            synchronized (OwlThreadPoolExecutor.class) {
                // double check
                if (threadPoolExecutorInstance == null || threadPoolExecutorInstance.isShutdown()) {
                    System.out.println("The thread pool instance is empty, so need to create.");
                    threadPoolExecutorInstance = new ThreadPoolExecutor(
                            corePoolSize,
                            maxPoolSize,
                            keepAliveTime,
                            TimeUnit.SECONDS,
                            new ArrayBlockingQueue<>(queueCapacity),
                            new OwlThreadFactory("ThreadPool"),
                            new ThreadPoolExecutor.CallerRunsPolicy());
                    System.out.println("The thread pool instance info: " + threadPoolExecutorInstance);
                }
            }
        }
        return threadPoolExecutorInstance;
    }
}

线程工厂:

package threadpool;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class OwlThreadFactory implements ThreadFactory {

    private String namePrefix;
    private final AtomicInteger nextId = new AtomicInteger(1);
    
    public OwlThreadFactory(String whatFeatureOfGroup) {
        namePrefix = "From OwlThreadFactory's " + whatFeatureOfGroup + "-Worker-"; // 线程池名字 + 线程名字前缀
    }
    
    @Override
    public Thread newThread(Runnable task) {
        String name = namePrefix + nextId.getAndIncrement(); // 线程id
        Thread thread = new Thread(null, task, name);
        return thread;
    }

}

执行的逻辑类代码:
(主要是输出线程名字+开始时间,然后休眠5秒,再输出线程名字+结束时间)

package threadpool;

import java.util.Date;

public class MyRunnable implements Runnable {

    private String name;
    
    public MyRunnable(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + ", name=" + name + ": Start. Time = " + new Date());
        processCommand();
        System.out.println(Thread.currentThread().getName() + ", name=" + name + ": End. Time = " + new Date());
    }

    private void processCommand() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

测试代码:

package threadpool;

import java.util.concurrent.ThreadPoolExecutor;

public class OwlThreadPoolExecutorTest {
    public static void main(String[] args) throws InterruptedException {
        
        ThreadPoolExecutor threadPoolExecutorInstance = OwlThreadPoolExecutor.getThreadPoolExecutorInstance();
        Runnable worker = new MyRunnable("李四");
        threadPoolExecutorInstance.execute(worker); // 执行一个任务
        
        Runnable worker2 = new MyRunnable("张三");
        threadPoolExecutorInstance.execute(worker2); // 再执行一个任务
        
        Runnable worker3 = new MyRunnable("王五");
        threadPoolExecutorInstance.execute(worker3); // 再执行一个任务
        
        Thread.sleep(5000);
        System.out.println("The thread pool instance info: " + threadPoolExecutorInstance);
    }
}

测试1,分析:
我们可以看到第一段代码:
private static int corePoolSize = 5;
private static int maxPoolSize = 10;
private static int queueCapacity = 100;
private static Long keepAliveTime = 1L;
这几个默认值,corePoolSize代表池中核心的线程数量,可以理解为池中常驻的线程数量,这里是5个;
maxPoolSize=maximumPoolSize, 代表池中可以存在线程最大数量,这里是10个;queueCapacity代表任务队列装载任务数量,这里是100个。

测试代码一共执行3个任务。

测试1,执行结果:

The thread pool instance is empty, so need to create.
The thread pool instance info: java.util.concurrent.ThreadPoolExecutor@6d06d69c[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0]
From OwlThreadFactory's ThreadPool-Worker-3, name=王五: Start. Time = Fri Feb 11 13:39:37 CST 2022
From OwlThreadFactory's ThreadPool-Worker-1, name=李四: Start. Time = Fri Feb 11 13:39:37 CST 2022
From OwlThreadFactory's ThreadPool-Worker-2, name=张三: Start. Time = Fri Feb 11 13:39:37 CST 2022
The thread pool instance info: java.util.concurrent.ThreadPoolExecutor@6d06d69c[Running, pool size = 3, active threads = 3, queued tasks = 0, completed tasks = 0]
From OwlThreadFactory's ThreadPool-Worker-2, name=张三: End. Time = Fri Feb 11 13:39:42 CST 2022
From OwlThreadFactory's ThreadPool-Worker-3, name=王五: End. Time = Fri Feb 11 13:39:42 CST 2022
From OwlThreadFactory's ThreadPool-Worker-1, name=李四: End. Time = Fri Feb 11 13:39:42 CST 2022

测试1,分析结果,通过The thread pool instance info: java.util.concurrent.ThreadPoolExecutor@6d06d69c[Running, pool size = 3, active threads = 3, queued tasks = 0, completed tasks = 0]
可以知道线程池中有3个core线程,因为都在运行中所以active threads = 3。执行这三个任务的线程是三个不同的线程maxPoolSize = 10;这个参数没有生效。


测试2,我们修改参数再测试看看变化(修改的部分加粗):
private static int corePoolSize = 1;
private static int maxPoolSize = 10;
private static int queueCapacity = 100;
private static Long keepAliveTime = 1L;

core线程数调成1,执行任务还是3个,看看结果:

The thread pool instance is empty, so need to create.
The thread pool instance info: java.util.concurrent.ThreadPoolExecutor@6d06d69c[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0]
From OwlThreadFactory's ThreadPool-Worker-1, name=李四: Start. Time = Fri Feb 11 13:43:35 CST 2022
The thread pool instance info: java.util.concurrent.ThreadPoolExecutor@6d06d69c[Running, pool size = 1, active threads = 1, queued tasks = 2, completed tasks = 0]
From OwlThreadFactory's ThreadPool-Worker-1, name=李四: End. Time = Fri Feb 11 13:43:40 CST 2022
From OwlThreadFactory's ThreadPool-Worker-1, name=张三: Start. Time = Fri Feb 11 13:43:40 CST 2022
From OwlThreadFactory's ThreadPool-Worker-1, name=张三: End. Time = Fri Feb 11 13:43:45 CST 2022
From OwlThreadFactory's ThreadPool-Worker-1, name=王五: Start. Time = Fri Feb 11 13:43:45 CST 2022
From OwlThreadFactory's ThreadPool-Worker-1, name=王五: End. Time = Fri Feb 11 13:43:50 CST 2022

测试2,分析结果,The thread pool instance info: java.util.concurrent.ThreadPoolExecutor@6d06d69c[Running, pool size = 1, active threads = 1, queued tasks = 2, completed tasks = 0]
core线程只有一个就是我们刚才改的一个,queue tasks是有2个在等待。执行这三个任务的线程都是同一个Worker-1maxPoolSize = 10;这个参数没有生效。

通过测试1和测试2,可以得出简单的结论如下:
<1>. 启动线程的数量首先是判断task数量是否大于core线程数量。
测试1,task=3 < coreThread=5 < queueCapacity=100,直接启动3个core线程,没有等待的task。
测试2,queueCapacity=100 > task=3 > coreThread=1,只能启动1个core线程,有2个等待的task。


测试3,我们修改参数再测试看看变化(修改的部分加粗):
private static int corePoolSize = 1;
private static int maxPoolSize = 10;
private static int queueCapacity = 1;
private static Long keepAliveTime = 1L;

core线程数是1,task队列容量调成1,执行任务还是3个,看看结果:

The thread pool instance is empty, so need to create.
The thread pool instance info: java.util.concurrent.ThreadPoolExecutor@6d06d69c[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0]
From OwlThreadFactory's ThreadPool-Worker-1, name=李四: Start. Time = Fri Feb 11 13:57:16 CST 2022
From OwlThreadFactory's ThreadPool-Worker-2, name=王五: Start. Time = Fri Feb 11 13:57:16 CST 2022
The thread pool instance info: java.util.concurrent.ThreadPoolExecutor@6d06d69c[Running, pool size = 2, active threads = 2, queued tasks = 1, completed tasks = 0]
From OwlThreadFactory's ThreadPool-Worker-1, name=李四: End. Time = Fri Feb 11 13:57:21 CST 2022
From OwlThreadFactory's ThreadPool-Worker-1, name=张三: Start. Time = Fri Feb 11 13:57:21 CST 2022
From OwlThreadFactory's ThreadPool-Worker-2, name=王五: End. Time = Fri Feb 11 13:57:21 CST 2022
From OwlThreadFactory's ThreadPool-Worker-1, name=张三: End. Time = Fri Feb 11 13:57:26 CST 2022

测试3,分析结果,The thread pool instance info: java.util.concurrent.ThreadPoolExecutor@6d06d69c[Running, pool size = 2, active threads = 2, queued tasks = 1, completed tasks = 0]
其实我们设置的core线程是1,但是这里居然起两个线程去执行task。这是由于maxPoolSize = 10这个参数生效了。
那它什么时候生效呢,看下面的结论。

通过之前的测试+测试3,可以得出结论:
<2>. 如果task=3 > coreThread=1 = queueCapacity容量=1,它就是去看最大线程数,最大线程数>core线程数那就再启动线程,直到等待的task量(queued tasks = 1)=queueCapacity 容量(queueCapacity = 1)。

所以线程池到底起多少个线程,首先是判断core线程数量,如果没有达到指定的数量,那么启动线程数直到task没有了(task数量 < core线程数量,如测试1)或者达到core线程数量(task数量 > core线程数量,如测试2);其次,一旦启动线程数达到core线程数量后,再判断剩余的task数量是否大于queueCapacity容量,如果剩余的task数量 < queueCapacity容量,那么就让剩下的task在队列中等待;如果剩余的task数量 > queueCapacity容量,那么就去判断最大的线程数(maxPoolSize ),如果maxPoolSize > coreThread,那么就再启动新的线程去执行task,知道剩下的task=queueCapacity容量,或者达到maxPoolSize指定的数量。如果task数量太大,大于core线程数量&最大线程数量&queueCapacity容量,那么就要看引用的reject策略(new ThreadPoolExecutor.CallerRunsPolicy()这个参数)了。

先测试这几个参数,后面应该还会更新。有任何问题都可以留言讨论。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值