Following the previous java-Thread Pool (I), I explained the benefits of the thread pool and common thread pools. This article parses the source code of the thread pool.
The thread pool highlights are as follows:
Executor
|
Interface, only execute method, put the task into the thread pool |
ExecutorService
|
Interface to inherit Executor and increase the thread state acquisition |
Executors
|
Class, task submission, and thread pool Category Selection |
ThreadPoolExecutor
|
Class, thread pool, responsible for task scheduling and Processing |
(1) Executor
Public interface Executor {/*** put the thread into the thread pool * @ param command the asynchronous task to be executed */void execute (Runnable command );}
The thread submission interface is provided in a unified manner. All thread pools must inherit from Chengdu.
(2) ExecutorService
Public interface ExecutorService extends Executor {void shutdown (); boolean isShutdown (); boolean isTerminated ();
Future
Submit (Callable
Task );
List
> InvokeAll (Collection
> Tasks) throws InterruptedException; // some methods are omitted}
On the basis of Executor, add the thread lifecycle control (termination, wakeup, etc)
(3) Executors
Separates the job submission and execution in the thread pool. This part is the job Submission Part and provides four basic thread pools.
public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue
()); }
public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue
())); }
public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue
()); }
public static ScheduledExecutorService newSingleThreadScheduledExecutor() { return new DelegatedScheduledExecutorService (new ScheduledThreadPoolExecutor(1)); }
Comparison of four thread pools
|
CorePoolSize
|
MaximumPoolSize
|
KeepAliveTime
|
WorkQueue
|
NewFixedThreadPool
|
NThreads
|
NThreads
|
0L
|
LinkedBlockingQueue
|
NewSingleThreadExecutor
|
1 |
1 |
0L |
LinkedBlockingQueue
|
NewCachedThreadPool
|
0 |
Integer. MAX_VALUE
|
60L |
SynchronousQueue
|
NewScheduledThreadPool
|
CorePoolSize
|
Integer. MAX_VALUE
|
0L
|
DelayedWorkQueue |
CorePoolSize: Minimum number of threads maintained by the thread pool
MaximumPoolSize: Maximum number of threads maintained by the thread pool
KeepAliveTime: retention time of thread destruction
WorkQueue: used task to save the queue
NewFixedThreadPool specifies the maximum number of threads.
NewSingleThreadExecutor provides a single-thread pool, which is suitable for executing tasks in sequence.
NewCachedThreadPool provides a buffer period of 60L for thread destruction. The maximum number of threads is unlimited. It is suitable for executing a large number of small tasks.
NewScheduledThreadPool can delay and regularly execute tasks.
(4) ThreadPoolExecutor
/*** Core method: the task is thrown to the thread pool * @ param command */public void execute (Runnable command) {if (command = null) throw new NullPointerException (); // if the number of threads is smaller than the basic number of threads, create a thread and execute the current task if (poolSize> = corePoolSize |! AddIfUnderCorePoolSize (command) {// if the number of threads is greater than or equal to the basic number of threads or the thread creation fails, the current task is placed in the work queue. If (runState = RUNNING & workQueue. offer (command) {// if no thread is currently executed, force the first thread task if (runState! = RUNNING | poolSize = 0) ensureQueuedTaskHandled (command);} // If the thread pool is not RUNNING or tasks cannot be placed into the queue, if the number of threads is less than the maximum number of threads allowed, a thread is created to execute the task. Else if (! AddIfUnderMaximumPoolSize (command) // when the task cannot be successfully received, handle the exception reject (command) according to the policy );}}
/*** Add a task to the Thread pool * @ param firstTask * @ return */private boolean addIfUnderCorePoolSize (Runnable firstTask) {Thread t = null; final ReentrantLock mainLock = this. mainLock; mainLock. lock (); try {// if (poolSize <corePoolSize & runState = RUNNING) t = addThread (firstTask);} finally {mainLock. unlock ();} return t! = Null ;}
/*** Enable a Thread for the task ** @ param firstTask * @ return */private Thread addThread (Runnable firstTask) {// worker represents a Thread, processing of the entire Thread. After the current task is completed, it will automatically take the queue task to execute Worker w = new Worker (firstTask); // Thread t = threadFactory created in factory mode. newThread (w); boolean workerStarted = false; if (t! = Null) {if (t. isAlive () // precheck that t is startable throw new IllegalThreadStateException (); w. thread = t; workers. add (w); int nt = ++ poolSize; // if (nt> largestPoolSize) largestPoolSize = nt (if> largestPoolSize) is no longer enabled when the current number of threads has reached the maximum; try {t. start (); workerStarted = true;} finally {if (! WorkerStarted) workers. remove (w) ;}} return t ;}
There are four types of system performance and thread pool creation, which have their respective advantages and disadvantages.
Next, we will discuss android Performance Optimization in detail. First, we will prepare basic knowledge.