[Interview] Interviewer: Tell me about the meaning of the 7 parameters of the thread pool?

foreword

The so-called seven parameters of the thread pool refer to the seven parameters set when using ThreadPoolExecutor to create a thread pool, as shown in the following source code:

public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue,
                          ThreadFactory threadFactory,
                          RejectedExecutionHandler handler) {
    
    
    //...
}

The seven parameters are:

  1. corePoolSize: The number of core threads.
  2. maximumPoolSize: The maximum number of threads.
  3. keepAliveTime: Idle thread survival time.
  4. TimeUnit: time unit.
  5. BlockingQueue: thread pool task queue.
  6. ThreadFactory: A factory that creates threads.
  7. RejectedExecutionHandler: rejection strategy.

1. Parameter 1: corePoolSize

Number of core threads: refers to the number of long-term surviving threads in the thread pool.

This is like the big families in ancient times, they would hire some "long-term workers" to work for them for a long time. These people are generally relatively stable. No matter how much they work this year, these people will not be dismissed. other people's.

2. Parameter 2: maximumPoolSize

Maximum number of threads: The maximum number of threads allowed to be created by the thread pool, when the task queue of the thread pool is full, the maximum number of threads that can be created.

This is the maximum number of people that a large family can employ in ancient times. For example, when a certain festival or someone in a large family celebrates a birthday, because there are too many jobs, "long-term workers" alone cannot complete the task. At this time, some "short-term workers" will be recruited together. For work, the maximum number of threads is the total number of "long-term workers" + "short-term workers", that is, the number of recruits cannot exceed
the maximumPoolSize.

Precautions
The value of the maximum number of threads maximumPoolSize cannot be less than the number of core threads corePoolSize, otherwise an IllegalArgumentException will be reported when the program is running, as shown in the following figure:
insert image description here

3. Parameter 3: keepAliveTime

Idle thread survival time, when there are no tasks in the thread pool, some threads will be destroyed, the number of destroyed threads = maximumPoolSize (maximum number of threads) - corePoolSize (number of core threads).

Still take the big family as an example, when the big family is busy, they will hire some "part-time workers" to work, but after finishing the work, these "part-time workers" will be dismissed when they are not busy, and keepAliveTime is
used To describe the (maximum) time that a short-term worker can stay in a big family's family after he has no work.

4. Parameter 4: TimeUnit

Time unit: The description unit of the idle thread survival time, this parameter is used in conjunction with parameter 3.
Parameter 3 is a long type value, for example, parameter 3 passes 1, so this 1 means 1 day? Or 1 hour? Or 1 second? Parameter 4 has the final say.
TimeUnit has the following 7 values:

  1. TimeUnit.DAYS: days
  2. TimeUnit.HOURS: hours
  3. TimeUnit.MINUTES: minutes
  4. TimeUnit.SECONDS: seconds
  5. TimeUnit.MILLISECONDS: Milliseconds
  6. TimeUnit.MICROSECONDS: Subtle
  7. TimeUnit.NANOSECONDS: nanoseconds

5. Parameter 5: BlockingQueue

Blocking queue: The thread pool stores the task queue, which is used to store all pending tasks of the thread pool.
It can set the following values:

  • ArrayBlockingQueue: A bounded blocking queue composed of array structures.
  • LinkedBlockingQueue: A bounded blocking queue composed of a linked list structure.
  • SynchronousQueue: A blocking queue that does not store elements, i.e. submits directly to threads without holding them.
  • PriorityBlockingQueue: An unbounded blocking queue that supports priority sorting.
  • DelayQueue: An unbounded blocking queue implemented using a priority queue, from which elements can only be extracted when the delay expires.
  • LinkedTransferQueue: An unbounded blocking queue composed of a linked list structure. Similar to SynchronousQueue, also contains non-blocking methods.
  • LinkedBlockingDeque: A bidirectional blocking queue composed of a linked list structure.

LinkedBlockingQueue is more commonly used, and the queuing strategy of the thread pool is closely related to BlockingQueue.

6. Parameter 6: ThreadFactory

Thread factory: The factory method called when the thread pool creates a thread. Through this method, the thread priority, thread naming rules, and thread type (user thread or daemon thread) can be set.
An example of using a thread factory is as follows:

public static void main(String[] args) {
    
    
    // 创建线程工厂
    ThreadFactory threadFactory = new ThreadFactory() {
    
    
        @Override
        public Thread newThread(Runnable r) {
    
    
            // 创建线程池中的线程
            Thread thread = new Thread(r);
            // 设置线程名称
            thread.setName("Thread-" + r.hashCode());
            // 设置线程优先级(最大值:10)
            thread.setPriority(Thread.MAX_PRIORITY);
            //......
            return thread;
        }
    };
    // 创建线程池
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 10, 0,
                                                                   TimeUnit.SECONDS, new LinkedBlockingQueue<>(),
                                                                   threadFactory); // 使用自定义的线程工厂
    threadPoolExecutor.submit(new Runnable() {
    
    
        @Override
        public void run() {
    
    
            Thread thread = Thread.currentThread();
            System.out.println(String.format("线程:%s,线程优先级:%d",
                                             thread.getName(), thread.getPriority()));
        }
    });
}

The execution result of the above program is as follows:
insert image description here

It can be seen from the above execution results that the custom thread factory works, and the thread name and thread priority are set through the thread factory.

7. Parameter 7: RejectedExecutionHandler

Rejection strategy: The strategy executed when the tasks in the thread pool exceed the maximum value that can be stored in the thread pool queue.
There are 4 default rejection strategies:

  • AbortPolicy: Reject and throw an exception.
  • CallerRunsPolicy: Use the current calling thread to perform this task.
  • DiscardOldestPolicy: A task at the head of the queue (oldest) is discarded and the current task is executed.
  • DiscardPolicy: Ignore and discard the current task.

The default policy of the thread pool is AbortPolicy to reject and throw an exception.

Summarize

This article introduces the seven parameters of the thread pool:

  1. corePoolSize: the number of core threads, the number of threads held by the thread pool under normal conditions, and the number of "long-term workers" of big families.
  2. maximumPoolSize: the maximum number of threads, the maximum number of threads that can be owned when the thread pool is busy, and the total number of "long-term workers" + "short-time workers" of big families.
  3. keepAliveTime: The survival time of idle threads, the maximum time that "short-time workers" can survive after no activity.
  4. TimeUnit: Time unit, used together with parameter 3, used to describe the time unit of parameter 3.
  5. BlockingQueue: The task queue of the thread pool, which is used to save the container of the tasks to be executed by the thread pool.
  6. ThreadFactory: thread factory, a factory method for creating threads in the thread pool, through which the naming rules, priority and thread type of threads can be set.
  7. RejectedExecutionHandler: Rejection strategy, when the amount of tasks exceeds the maximum number of tasks that the thread pool can save, the execution strategy.

Guess you like

Origin blog.csdn.net/u011397981/article/details/130534510