The seven parameters of a thread pool are the seven parameters that are set when creating a thread pool using ThreadPoolExecutor, as shown in the source code below:

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

The 7 parameters are:

  1. CorePoolSize: number of core threads.
  2. MaximumPoolSize: indicates the maximum number of threads.
  3. KeepAliveTime: indicates the keepAliveTime of idle threads.
  4. TimeUnit: TimeUnit.
  5. BlockingQueue: Thread pool task queue.
  6. ThreadFactory: Factory for creating threads.
  7. RejectedExecutionHandler: reject the policy.

Parameter 1: corePoolSize

Number of core threads: Refers to the number of threads in the thread pool that are alive for a long time.

This is just like the big families in ancient times, they would hire some “permanent workers” to work for them for a long time. These people are generally stable. No matter how much they live in this year, these people will not be fired, and they are living in big families for a long time.

Parameter 2: maximumPoolSize

Maximum number of threads: The maximum number of threads that can be created by a thread pool when the pool’s task queue is full.

This is the maximum number of people that a large family could employ in ancient times. For example, when someone in a large family celebrated his or her birthday, because of too much work, it was impossible to complete the task only by “permanent workers”, then some “temporary workers” would be recruited to work together. The maximum number of threads is the total number of “permanent workers” + “temporary workers”. That is, the number of people recruited cannot exceed maximumPoolSize.

Matters needing attention

The maximum number of threads maximumPoolSize cannot be smaller than the number of core threads corePoolSize. Otherwise, IllegalArgumentException will be reported when the program runs.

Parameter 3: keepAliveTime

The number of threads destroyed when there are no tasks in the thread pool =maximumPoolSize -corePoolSize

KeepAliveTime is a keepAliveTime to describe the length of time that a temporary worker can stay in a large house when there is no work.

Parameter 4: TimeUnit

Time unit: a descriptive unit of the lifetime of idle threads. This parameter is used in conjunction with parameter 3. Parameter 3 is a value of type long. For example, if parameter 3 passes 1, then the 1 represents 1 day, right? Or an hour? Or one second? Is determined by parameter 4. TimeUnit has the following seven values:

  1. TimeUnit. DAYS: day
  2. TimeUnit. HOURS: HOURS
  3. TimeUnit. MINUTES: points
  4. TimeUnit. SECONDS: SECONDS
  5. TimeUnit. MILLISECONDS: ms
  6. TimeUnit. MICROSECONDS: subtle
  7. TimeUnit. NANOSECONDS: NANOSECONDS

Parameter 5: BlockingQueue

Blocking queue: A queue that holds tasks in a thread pool and is used to store all pending tasks in the thread pool. It can set the following values:

  1. ArrayBlockingQueue: A bounded blocking queue composed of array structures.
  2. LinkedBlockingQueue: A bounded blocking queue consisting of a linked list structure.
  3. SynchronousQueue: A blocking queue that does not store elements, that is, submitted directly to threads without holding them.
  4. PriorityBlockingQueue: An unbounded blocking queue that supports priority sorting.
  5. DelayQueue: an unbounded blocking queue implemented using a priority queue from which elements can only be extracted when the delay expires.
  6. LinkedTransferQueue: An unbounded blocking queue consisting of a linked list structure. Like SynchronousQueue, it also has non-blocking methods.
  7. LinkedBlockingDeque: A bidirectional blocking queue consisting of a linked list structure.

A common one is LinkedBlockingQueue, and the queueing policy of the thread pool is related to BlockingQueue.

Parameter 6: ThreadFactory

Thread factory: A factory method that is called when a thread is created by a thread pool. This method allows you to set the priority of the thread, the thread naming convention, and the thread type (user or daemon). An example of a thread factory is as follows:

public static void main(String[] args) {
    // Create a thread factory
    ThreadFactory threadFactory = new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            // Create a thread in the thread pool
            Thread thread = new Thread(r);
            // Set the thread name
            thread.setName("Thread-" + r.hashCode());
            // Set thread priority (Max. : 10)
            thread.setPriority(Thread.MAX_PRIORITY);
            / /...
            returnthread; }};// Create a thread pool
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10.10.0,
                                                                   TimeUnit.SECONDS, new LinkedBlockingQueue<>(),
                                                                   threadFactory); // Use custom thread factories
    threadPoolExecutor.submit(new Runnable() {
        @Override
        public void run(a) {
            Thread thread = Thread.currentThread();
            System.out.println(String.format("Thread: %s, thread priority: %d", thread.getName(), thread.getPriority())); }}); }Copy the code

The execution results of the above procedures are as follows:As you can see from the above results, the custom thread factory works, and the thread name and thread priority are set through the thread factory.

Parameter 7: RejectedExecutionHandler

Reject policy: The policy that is executed when the number of tasks in a thread pool exceeds the maximum number that a thread pool queue can store. The default rejection policies are as follows:

  • AbortPolicy: Rejects and throws an exception.
  • CallerRunsPolicy: Perform this task using the thread currently invoked.
  • DiscardOldestPolicy: Discards a task at the head (oldest) of the queue and executes the current task.
  • DiscardPolicy: Ignores and discards the current task.

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

conclusion

This article describes the seven parameters of a thread pool:

  1. CorePoolSize: the number of core threads, the number of threads that the thread pool normally maintains, and the number of “long workers” in a large household.
  2. MaximumPoolSize: the maximum number of threads that a large household can have when the pool is busy, the total number of “long workers” + “short workers”.
  3. KeepAliveTime: keepAliveTime of idle threads, the maximum time that a “temp” can live without work.
  4. TimeUnit: TimeUnit. Used together with parameter 3, this parameter describes the TimeUnit of parameter 3.
  5. BlockingQueue: A thread pool task queue, used to hold the container for thread pool tasks to be executed.
  6. ThreadFactory: ThreadFactory, a factory method for creating threads in a thread pool that allows you to set thread naming conventions, priorities, and thread types.
  7. RejectedExecutionHandler: Reject the policy to be implemented when the number of tasks in the thread pool exceeds the maximum number of tasks that can be stored.

Judge right and wrong from yourself, praise to listen to others, gain and loss in the number.

Public number: Java interview analysis

Interview collection: gitee.com/mydb/interv…