Java thread pool Learning (5) -- ThreadPoolExecutor source code analysis
Through the previous chapter, we learned how to create a thread pool through ThreadPoolExecutor.
Next we will analyze the source code of ThreadPoolExecutor to see how it works.
Let's take a look at what happened when running a task using execute (Runnable task) (code is simplified ):
First, let's briefly describe what happens when we submit a task to the thread pool:
The source code is as follows:
Public void execute (Runnable task) {// retrieves the number of active threads in the current thread pool. // Ctl is an atomic object (final AtomicInteger ctl) used to save the number of threads in the current thread pool and the status of the thread pool. Int c = ctl. get (); // if the number of active threads is smaller than the number of core threads, a new thread is created even if there are Idle threads to execute this task if (workerCountOf (c) <corePoolSize) {// create a new thread to execute this task. If (addWorker (task, true) return; // if this statement is executed, the task is not allocated successfully. // Obtain the status value of the current thread pool to prepare for subsequent checks. C = ctl. get () ;}// if it is greater than the number of core threads, check whether the thread pool is still running and try to put the task into the blockingQueue task queue. If (isRunning (c) & workQueue. offer (task) {// check the thread pool status int recheck = ctl. get (); if (! IsRunning (recheck) & remove (task) // If the thread pool is not running, remove the task we just added to the task queue and reject the task. Reject (task); // check if the number of threads in the current thread pool is 0, create a new thread for the thread pool (because it is possible that the previous surviving thread died after the previous check) else if (workerCountOf (recheck) = 0) addWorker (null, false );} // This statement indicates that the queue is full. At this time, if the number of threads in the current thread pool has not exceeded the maximum number of threads, a new thread is created to execute this task. If it fails, the task is rejected. Else if (! AddWorker (task, false) reject (task );}
The above is the basic execution process of ThreadPoolExecutor.