Thread pool composition
A thread pool consists of the following four basic components:
1. Thread pool Manager (ThreadPool): Used to create and manage thread pools, including creating a thread pool, destroying the thread pool, adding new tasks;
2, worker thread (poolworker): Thread pool threads, in the absence of a task in the waiting state, you can cycle the execution of tasks;
3, Task interface (tasks): Each task must be implemented by the interface for the task of scheduling the execution of tasks, it mainly specifies the entry of the task, the completion of the task after the end of the task, the implementation of the mission status, etc.;
4. Task Queue (Taskqueue): Used to store tasks that are not processed. Provides a buffering mechanism.
Thread pool Type
1, Newsinglethreadexecutor
Creates a single thread pool that runs as a unbounded queue. This thread pool has only one thread working (if the only thread ends up with an exception, a new thread will replace it.) This thread pool ensures that all tasks are executed in the order in which they are submitted, with only one task running at a time.
This type of thread pool is particularly suitable for situations where the order of execution needs to be guaranteed.
2, Newfixedthreadpool
Creates a fixed-size thread pool that runs as a unbounded queue. When the thread pool is full and the threads are active, they wait until the wired thread is available if new tasks are submitted. Once the maximum size of the thread pool is reached, the thread pool will be replenished with a new thread if it ends up executing an exception. An explicit call to shutdown will close the thread pool.
This type of thread pool is more commonly used.
3, Newcachedthreadpool
Creates a cacheable pool of threads. When necessary, creating a new thread to process the request will also reuse threads in the thread pool that are already in the available state. If the size of the thread pool exceeds the thread that is required to process the task, then a partially idle (60 second non-performing task) thread is reclaimed, and when the number of tasks increases, the thread pool can intelligently add new threads to handle the task. This thread pool does not limit the size of the thread pool, and the thread pool size depends entirely on the maximum thread size that the operating system (or JVM) can create.
This type of thread pool is especially suitable for situations where time is short and synchronization is not required.
4, Newscheduledthreadpool
Create a thread pool that can run at timed intervals (initial delay), how often it runs (every few hours, or how long it takes to run successfully).
This type of thread pool is suitable for timed and recurring tasks.
JDK implementation of thread pool
The role of corepoolsize
In the generated thread pool threadpoolexecutor, there is a corepoolsize property that is used to determine if a new thread is to be created, and if the number of threads in the current thread pool is greater than corepoolsize, then there are idle threads. A thread is created without an idle thread. If it is less than corepoolsize, the new thread will be created anyway.
/** * Core Pool size, updated only and holding mainlock, but volatile to allow concurrent readability even dur ing updates. */ private volatile int corepoolsize;
Response of different thread pool types when executing the thread pool's Execute method
public void Execute (Runnable command) { if (command = = null) throw new NullPointerException (); if (poolsize >= corepoolsize | |!addifundercorepoolsize (command)) { if (runstate = = RUNNING && workqueue.o Ffer (command)) { if (runstate! = RUNNING | | poolsize = = 0) ensurequeuedtaskhandled (command); } else if (!addifundermaximumpoolsize command) reject (command);//is shutdown or saturated } }
Worker threads
After the worker thread executes its run method, it tries to wait for the task to be removed from the queue.
/** * Main run loop * /public void Run () { try { hasrun = true; Runnable task = Firsttask; Firsttask = null; while (task! = NULL | | (Task = Gettask ()) = null) {//Note gettask () method, which loops to fetch the task runTask (Task); task = null; } } finally { workerdone (this); } }
See Gettask () method
It's going to cycle out and take out tasks,
Runnable Gettask () {for (;;) {try {int state = Runstate; if (State > SHUTDOWN) return null; Runnable R; if (state = = SHUTDOWN)//help drain queue r = Workqueue.poll (); else if (poolsize > Corepoolsize | | allowcorethreadtimeout) R = Workqueue.poll (KeepAliveTime, Timeun It. nanoseconds); else R = Workqueue.take (); Note that for a fixed-size thread pool and a buffered thread pool, the queue type used is different, one is blocking the queue, and one is the synchronous queue if (r! = null) return r; if (Workercanexit ()) {//Gets no task, there is an exit mechanism for the buffered queue if (runstate >= SHUTDOWN)//Wake up others Interruptidleworkers (); return null; }//Else retry} catch (Interruptedexception IE) {//on interruption, re-check Runstate}} }
Thread pool analysis of the JDK