Java. util. concurrent
Class ThreadPoolExecutor
Usage: Create a ThreadPoolExecutor object based on the constructor and execute the task.
Constructor:
Public ThreadPoolExecutor (int corePoolSize, // core processing pool capacity, the pool will keep so many threads alive int maximumPoolSize, // maximum processing pool, when the cache queue is full, the thread pool adds new processing threads to maximumPoolSize. If a task is added at this time, long keepAliveTime is rejected. // The worker thread obtains the task timeout time. For details, see TimeUnit unit, // time unit BlockingQueue <Runnable> workQueue) // task queue
Explanation of core code:
Execute method execution process is as follows: 1. If the number of currently running threads is less than the configured core pool, the worker thread is started; otherwise, the queue is in; 2. If the queue is full, start the worker thread again. 3. If the running worker thread is greater than the configured maximumPoolSize, the task is rejected.
Public void execute (Runnable command) {if (command = null) throw new NullPointerException (); // if the running thread is smaller than the core pool, a new worker thread is started, otherwise, if (poolSize> = corePoolSize |! AddIfUnderCorePoolSize (command) {// inbound queue if (runState = RUNNING & workQueue. offer (command) {if (runState! = RUNNING | poolSize = 0) ensureQueuedTaskHandled (command);} // if the queue is full, a new thread is started until the number of worker threads reaches maximumPoolSize. Otherwise, else if (! AddIfUnderMaximumPoolSize (command) reject (command); // is shutdown or saturated }}
Worker thread explanation:
When the worker thread starts, it comes with a task. After the task is executed, it gets the task from the task queue. Here, the worker thread obtains the task in two different situations, 1. When the number of worker threads is greater than corePoolSize, there is a timeout value for the retrieved task. If the timeout value is exceeded, the task is not obtained. The timeout value is the keepAliveTime set in the constructor ), terminate the current worker thread. 2. When the number of worker threads is less than or equal to corePoolSize, the worker thread waits until the task is obtained.
In addition, the execute method in ThreadPoolExecutor must be an object that implements the Runnable interface. In fact, it is necessary to call the run method of this object in the worker thread. That is to say, the task executed by the execute has no new thread, task execution is performed in the worker thread.
This article is from the "goat Knight" blog, please be sure to keep this source http://xingvs.blog.51cto.com/7657438/1300174