Starting with Java 5, Java provides its own thread pool. A thread pool is a container of threads that only perform the rated number of threads at a time. Java.util.concurrent.ThreadPoolExecutor is such a thread pool. It is very flexible, but it is also more complex to use, this article will make an introduction to it.
The first is the constructor. Take the simplest constructor as an example:
public ThreadPoolExecutor(
int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue)
It looks very complicated. here to introduce.
Corepoolsize refers to the size of the reserved thread pool.
Maximumpoolsize refers to the maximum size of the thread pool.
KeepAliveTime refers to the timeout for the end of an idle thread.
Unit is an enumeration that represents the units of a keepalivetime.
Workqueue represents the queue that holds the task.
We can understand the meaning of these parameters from the thread pool's working process. The thread pool works as follows:
1, when the line Chengchigang is created, there is not a thread inside. The task queue is passed in as a parameter. However, even if there are tasks in the queue, the thread pool will not execute them immediately.
2. When the Execute () method is invoked to add a task, the thread pool makes the following judgments:
A. If the number of threads running is less than corepoolsize, create a thread to run the task immediately;
B. If the number of threads running is greater than or equal to corepoolsize, put this task into the queue.
C. If the queue is full and the number of threads running is less than maximumpoolsize, create a thread to run the task;
D. If the queue is full and the number of threads running is greater than or equal to maximumpoolsize, the thread pool throws an exception telling the caller "I can't accept the task anymore".
3, when a thread completes the task, it takes the next task from the queue to execute.
4, when a thread has nothing to do, more than a certain amount of time (KeepAliveTime), the thread pool will determine if the current number of threads running more than corepoolsize, then the thread is stopped. So when all the tasks of the thread pool are complete, it eventually shrinks to the size of the corepoolsize.