Objective:
This article mainly introduces the benefits of using the thread pool and the Executorservice interface, and then learns to generate a simple thread pool that meets different needs through the Executors factory class, but sometimes we need to customize a thread pool when we have a relatively complex thread pool. Learn about Threadpoolexecutor today, and then use the scenario to define a thread pool of tasks to be performed by thread priority.
Threadpoolexecutor
The threadpoolexecutor thread pool is used to manage the Threads task queue, several threads.
1.) Threadpoolexecutor Constructor
Threadpoolexecutor (intCorepoolsize,intMaximumpoolsize,LongKeepalivetime,timeunit unit,blockingqueue<runnable>workQueue) Threadpoolexecutor (intCorepoolsize,intMaximumpoolsize,LongKeepAliveTime, Timeunit unit,blockingqueue Workqueue,rejectedexecutionhandler handler) Threadpoolexecutor (intCorepoolsize,intMaximumpoolsize,LongKeepalivetime,timeunit unit,blockingqueue<runnable>Workqueue,rejectedexecutionhandler Handler) Threadpoolexecutor (intCorepoolsize,intMaximumpoolsize,LongKeepalivetime,timeunit unit,blockingqueue<runnable> workqueue,threadfactory ThreadFactory, Rejectedexecutionhandler handler)
Corepoolsize: Thread pool maintains a minimum number of threads
Maximumpoolsize: Thread pool maintains the maximum number of threads
KeepAliveTime: The thread pool maintains the idle time allowed by threads
Unit: The thread pool maintains the units of idle time allowed by threads
WorkQueue: Buffer queue used by the thread pool
Threadfactory: Thread pool used to create threads
Handler: thread pool processing policy for rejected tasks
2.)Create a new thread
The default is to use Executors.defaultthreadfactory (), or by using the following method
/** * Create thread factory */ privatestaticfinalnew Threadfactory () { privatefinalnew Atomicinteger (1); @Override public Thread newthread (Runnable Runnable) { return New Thread (runnable, "download#" + mcount.getandincrement ()); } };
3.)Thread Creation Rules
When the Threadpoolexecutor object is initialized, no execution threads are created and the execution thread is created when a new task comes in. When constructing a Threadpoolexecutor object, you need to configure the object's core thread pool size and maximum thread pool size
1. When the total number of threads currently executing is less than the core thread size, all newly added tasks are processed in the new thread.
2. When the total number of threads currently executing is greater than or equal to the core thread, all newly added tasks are placed in the task cache queue.
3. When the total number of threads currently executing is greater than or equal to the core thread, and the cache queue is full and the total number of threads is less than the maximum size of the thread pool, create a new thread, join the thread pool, and assist with the new task.
4. When all threads are executing, the thread pool size has reached the upper limit, and the cache queue is full, Rejecthandler rejects the new task.
4.) Default Rejectexecutionhandler deny execution policy
1. AbortPolicy discards the new task directly and throws the Rejectedexecutionexception notification caller, the task is discarded
2. Callerrunspolicy use the caller's thread to perform a new task, and if the task execution is in strict order, do not use this policy
3. Discardpolicy silently discards the task, does not inform the caller, when processing the network message, may use this task, silently discards the not nearly processing the message
4. Discardoldestpolicy discards the oldest task and can use this task when dealing with network messages, because the message processing is time-lapse and must be discarded
We can also write some of our own rejectedexecutionhandler, such as rejecting, directly joining the thread to the cache queue, blocking the caller, or discarding the task beyond the limit based on the timestamp of the task.
5.) Task Queue Blockingqueue
Queuing principle
1. If the thread running is less than corepoolsize, Executor always prefers to add a new thread without queuing.
2. If the thread running is equal to or more than corepoolsize, Executor always prefers to join the request to the queue without adding a new thread.
3. If the request cannot be queued, a new thread is created unless the thread is created beyond maximumpoolsize, in which case the task is rejected.
Several common Blockingqueue implementations
1. Arrayblockingqueue: bounded array queue
2. Linkedblockingqueue: can support bounded/unbounded queues, using linked list implementation
3. Priorityblockingqueue: Priority queue, can be sorted for tasks
4. Synchronousqueue: Queue Length of 1 queues, and array a little difference is that: the client thread commits to the block queue will be a blocking process until a worker thread is connected to poll task.
6.) Thread pool execution
Execute () method, three private methods are called
Addifundercorepoolsize (): If the thread pool size is smaller than the core thread pool size, the expansion thread pool
Addifundermaximumpoolsize (): If the thread pool size is smaller than the thread pool size limit, the expansion thread pool
Ensurequeuedtaskhandled (): To ensure that the thread pool is closed, new queue threads are also handled correctly
7.) Thread pool shutdown
Shutdown (): Does not terminate the thread pool immediately, but waits until all tasks in the task cache queue have been executed before terminating, but will no longer accept new tasks
Shutdownnow (): Terminates the thread pool immediately, attempts to break the task in progress, and empties the task cache queue, returning tasks that have not yet been performed
Threadpoolexecutor Implementing a priority thread pool 1.) Defining thread Precedence enumeration
/***/publicenum priority {High , NORMAL, low}
2.) Define thread tasks
/*** runnable type with priority*//* Package*/ classPriorityrunnableImplementsRunnable { Public FinalPriority priority;//Task Priority Private FinalRunnable Runnable;//Task Real Performer /* Package*/ LongSEQ;//Task unique Indication Publicpriorityrunnable (Priority priority, Runnable Runnable) { This. Priority = Priority = =NULL?Priority.NORMAL:priority; This. runnable =runnable; } @Override Public Final voidrun () { This. Runnable.run (); }}3.) Define a Priorityexecutor inheritance Threadpoolexecutor
Public classPriorityexecutorextendsThreadpoolexecutor {Private Static Final intCore_pool_size = 5;//core thread pool size Private Static Final intMaximum_pool_size = 256;//maximum thread pool queue size Private Static Final intkeep_alive = 1;//The maximum time that an idle thread can remain alive while the number of threads is greater than corepoolsize. Private Static FinalAtomiclong Seq_seed =NewAtomiclong (0);//main get Add Task /*** Create thread factory*/ Private Static FinalThreadfactory sthreadfactory =Newthreadfactory () {Private FinalAtomicinteger MCount =NewAtomicinteger (1); @Override PublicThread newthread (Runnable Runnable) {return NewThread (runnable, "download#" +mcount.getandincrement ()); } }; /*** Thread queue mode FIFO first*/ Private Static FinalComparator<runnable> FIFO =NewComparator<runnable>() {@Override Public intCompare (Runnable lhs, Runnable rhs) {if(LHSinstanceofPriorityrunnable && RHSinstanceofpriorityrunnable) {priorityrunnable lpr=((priorityrunnable) LHS); Priorityrunnable RPR=((priorityrunnable) RHS); intresult = Lpr.priority.ordinal ()-rpr.priority.ordinal (); returnresult = = 0? (int) (LPR. SEQ-RPR. SEQ): result; } Else { return0; } } }; /*** Thread queue mode LIFO*/ Private Static FinalComparator<runnable> LIFO =NewComparator<runnable>() {@Override Public intCompare (Runnable lhs, Runnable rhs) {if(LHSinstanceofPriorityrunnable && RHSinstanceofpriorityrunnable) {priorityrunnable lpr=((priorityrunnable) LHS); Priorityrunnable RPR=((priorityrunnable) RHS); intresult = Lpr.priority.ordinal ()-rpr.priority.ordinal (); returnresult = = 0? (int) (RPR. SEQ-LPR. SEQ): result; } Else { return0; } } }; /*** Default number of worker threads 5 * *@paramFIFO priority is the same, waiting for the queue priority to perform the first join task. */ PublicPriorityexecutor (BooleanFIFO) { This(Core_pool_size, FIFO); } /** * @parampoolsize Number of worker threads *@paramFIFO priority is the same, waiting for the queue priority to perform the first join task. */ PublicPriorityexecutor (intPoolsize,BooleanFIFO) { This(Poolsize, Maximum_pool_size, keep_alive, Timeunit.seconds,NewPriorityblockingqueue<runnable> (Maximum_pool_size, FIFO?)Fifo:lifo), sthreadfactory); } PublicPriorityexecutor (intCorepoolsize,intMaximumpoolsize,LongKeepAliveTime, Timeunit unit, blockingqueue<runnable>WorkQueue, Threadfactory threadfactory) { Super(Corepoolsize, maximumpoolsize, KeepAliveTime, Unit, WorkQueue, threadfactory); } /*** Determine if the current thread pool is busy *@return */ Public BooleanisBusy () {returnGetactivecount () >=getcorepoolsize (); } /*** Submit a task *@paramrunnable*/@Override Public voidExecute (Runnable Runnable) {if(runnableinstanceofpriorityrunnable) {((priorityrunnable) runnable). SEQ=seq_seed.getandincrement (); } Super. Execute (runnable); }}
There are two types of thread queue patterns defined: FIFO (LIFO) LIFO (last-in, first-out) with the same priority as the order of submission
4.) Test procedure
Executorservice Executorservice =NewPriorityexecutor (5,false); for(inti = 0; I < 20; i++) {priorityrunnable priorityrunnable=NewPriorityrunnable (Priority.normal,NewRunnable () {@Override Public voidrun () {LOG.E (TAG, Thread.CurrentThread (). GetName ()+ "Priority normal"); } }); if(i% 3 = = 1) {priorityrunnable=NewPriorityrunnable (Priority.high,NewRunnable () {@Override Public voidrun () {LOG.E (TAG, Thread.CurrentThread (). GetName ()+ "High priority"); } }); } Else if(i% 5 = = 0) {priorityrunnable=NewPriorityrunnable (Priority.low,NewRunnable () {@Override Public voidrun () {LOG.E (TAG, Thread.CurrentThread (). GetName ()+ "Low Priority"); } }); } executorservice.execute (priorityrunnable); }
Running results: It is not difficult to find that priority high basically performs the final implementation of the basic priority is relatively low
Android thread management Threadpoolexecutor custom thread pool (iii)