Seven core parameters and execution process of thread pool

Seven core parameters of thread pool

1.corePoolSize (number of core threads)

2.maxPoolSize (maximum number of threads)

3.keepAliveTime (idle recovery time)

4.unit (recovery time unit)

5.workQueue (task queue)

6.threadFactory (thread factory, used to create threads, usually the default thread factory)

7.handler (rejection strategy)

 

When the execute(() method is called to add a request task, the thread pool will make the following judgments ::

When the number of thread creation tasks is less than the number of core threads corePoolSize, it is directly created and executed, and when the number of thread creation tasks is greater than the number of core threads, it is added to the task queue workQueue

(Common tasks queue has bounded queue : 1.ArrayBlockingQueue, 2.SynchronousQueue,

Unbounded queue: 1. LinkedBlockingQueue, not detailed yet. )wait,

When the task queue is also full, check to see if it is greater than the maximum number of threads maxPoolSize. If the queue is full and the number of running threads is less than naximumPoolSize, then you still have to create a non-core thread to run the task immediately, if it is greater than the maximum number of threads, then Execute rejection policy handler

(There are four rejection strategies:

1. CallerRunsPolicy: This strategy retries to add the current task, and it will automatically call the execute() method repeatedly until it succeeds.

2. AbortPolicy: Abandon the rejected task and throw an exception.

3. DiscardPolicy: Directly silently discard the rejected task without abnormal information.

4. DiscardOldestPolicy: Do not discard the rejected task, but discard the thread that has been waiting the longest in the queue, and then add the rejected task to the queue.

) If not, create and execute. When a thread completes its task, it will take the next task from the queue to execute. When a thread has nothing to do for more than a certain time (keepAliveTime)), the thread pool will judge: if the number of currently running threads is greater than corePoolSize, then this thread will be stopped. So after all tasks of the thread pool are completed, it will eventually shrink to the size of corePoolSize.

Guess you like

Origin blog.csdn.net/qq_37980436/article/details/105070229