The working mechanism of ThreadPoolExecutor:
The task processing of the entire ThreadPoolExecutor has 4 steps:
- The first step, the initial poolSize < corePoolSize, the submitted runnable task will be directly used as the parameter of a new Thread, executed immediately, and return
- In the second step, when the number of submitted tasks exceeds the corePoolSize, the second step is entered. Will submit the current runable to a block queue, if the submission is successful, return
- In the third step, if poolSize < maximumPoolsize, it will try to create a new Thread for emergency treatment, and immediately execute the corresponding runnable task
- The fourth step, if the add thread is successful and the current task is just scheduled for execution, return
- Step 5: The add thread fails, reject, otherwise it means that the add thread can still be added , but the task being executed is not the current task, repeat 12345, and try again until the submission is successful or rejected.
-- In the case where task processing is slow and the queue is full, the number of threads in the thread pool will quickly reach maxPoolSize)
Calling execute is enough, no need to call submit()
JDK1.5 impl:
===================================================
ThreadPoolExecutor number of threads
After the executor is constructed, the initial number of threads in the thread pool is 0, and the creation of threads will only be triggered when the task is responded to.
corePoolSize the number of threads to keep in the pool, even if they are idle.
maximumPoolSize the maximum number of threads to allow in the pool.
-----------------------
线程对象只有在线程执行完毕后,才会被回收,所以只要线程池没有被shutdown,则ThreadPoolExecutor无法被回收