Many common components commonly found in Android are often inseparable from the concept of "pooling", such as various image loading libraries, network request libraries, even if the Meaasge in the Android messaging mechanism is used Meaasge.obtain () is the object in the Meaasge pool, So the concept is important. The thread pooling technique described in this article also conforms to this idea.
-
Benefits of the thread pool:
reusing threads in a thread pool, reducing the performance overhead associated with object creation and destruction;
Can effectively control the maximum number of concurrent threads, improve system resource utilization, while avoiding excessive resource competition, avoid clogging;
can be multi-threaded simple management, so that the use of threads simple, efficient.
- Thread Pool Framework Executor
The thread pool in Java is implemented through the Executor framework, and the Executor framework includes classes: Executor,executors,executorservice,threadpoolexecutor, callable and future, The use of futuretask and so on.
Executor: There is only one method for all thread pool interfaces.
Public Interface executor{ void execute (Runnable command);}
Executorservice: Increasing the behavior of executor is the most direct interface to the executor implementation class.
Executors: Provides a series of factory methods for creating a first thread pool, and the returned thread pool implements the Executorservice interface.
Threadpoolexecutor: The specific implementation class of the thread pool, the various thread pools used in general are based on this class implementation.
The construction method is as follows:
Public Threadpoolexecutor (int corepoolsize, int maximumpoolsize, Long KeepAliveTime, timeunit unit, blockingqueue<Runnable> workQueue) { This (Corepoolsize,maximumpoolsize,keepalivetime,unit,workqueue,executors.defaultthreadfactory (), DefaultHandler);}
Parameter Description:
Corepoolsize: The number of core threads in the thread pool, the number of threads running in the threads pools will never exceed corepoolsize, and will survive by default. You can set Allowcorethreadtimeout to true, at which point the number of core threads is 0, at which time the KeepAliveTime controls the timeout for all threads.
Maximumpoolsize: The maximum number of threads allowed by the thread pool;
KeepAliveTime: Refers to the time-out for idle threads to end;
Unit: Is an enumeration that represents the units of the KeepAliveTime;
WorkQueue: Represents the blockingqueue<runnable queue that holds the task.
Blockingqueue: The blocking queue (Blockingqueue) is a tool that is primarily used to control thread synchronization under Java.util.concurrent. If the blockqueue is empty, the operation from the Blockingqueue will be blocked into the waiting state until the blockingqueue enters something to be awakened. Similarly, if the blockingqueue is full, any attempt to store something in it will be blocked into the waiting state until there is space in the blockingqueue to be woken up to continue operation.
blocking queues are often used for producer and consumer scenarios, where the producer is the thread that adds elements to the queue, and the consumer is the thread that takes the elements from the queue. The blocking queue is the container where the producer stores the elements, and the consumer only takes the elements from the container. The concrete realization class has linkedblockingqueue,arrayblockingqueued and so on. In general, the internal is through lock and condition (lock) and condition learning and use to achieve blocking and wake-up.
3. Working process of the thread pool
When a line Chengchigang is created, there is no thread inside. The task queue is passed in as a parameter. However, even if there are tasks in the queue, the thread pool does not execute them immediately.
When the Execute () method is called to add a task, the thread pool makes the following judgment:
If the number of threads running is less than corepoolsize, then create the thread to run the task immediately;
If the number of threads running is greater than or equal to Corepoolsize, the task is placed in the queue;
If the queue is full and the number of threads running is less than maximumpoolsize, then create a non-core thread to run the task immediately;
If the queue is full and the number of threads running is greater than or equal to maximumpoolsize, the thread pool throws an exception rejectexecutionexception.
When a thread finishes a task, it takes the next task from the queue to execute.
When a thread has nothing to do, more than a certain amount of time (KeepAliveTime), the thread pool will determine if the number of threads currently running is greater than corepoolsize, then the threads will be stopped. So when all the thread pool tasks are completed, it eventually shrinks to the size of the corepoolsize.
4. Creation and use of thread pools
The build thread pool takes a static approach to the tool class executors, and here are a few common thread pools.
1) Singlethreadexecutor: Single background thread (its buffer queue is unbounded)
Public Static Executorservice Newsinglethreadexecutor () { returnnew Finalizabledelegatedexecutorservice ( new threadpoolexecutor (1, 1, 0L, Timeunit.milliseconds, new linkedblockingqueue<runnable>())); }
Creates a single threaded pool of threads. This thread pool has only one core thread at work, which is equivalent to single thread serial execution of all tasks. If this unique thread ends because of an exception, a new thread will replace it. This thread pool guarantees that the order in which all tasks are executed is performed in the order in which the tasks are submitted.
2) Fixedthreadpool: Only the thread pool of the core thread, fixed size (its buffer queue is unbounded).
Public Static Executorservice newfixedthreadpool (int nthreads) { returnnew Threadpoolexecutor (Nthreads, nthreads, 0L, timeunit.milliseconds, new Linkedblockingqueue<runnable>()); }
Creates a fixed-size thread pool. Each time a task is committed, a thread is created until the thread reaches the maximum size of the threads pool. 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.
3) Cachedthreadpool: No boundary pool, can be automated process recovery.
Public Static Executorservice Newcachedthreadpool () { returnnew threadpoolexecutor (0, Integer.max_value, 60L, timeunit.seconds, new synchronousqueue<runnable> ()); }
If the size of the thread pool exceeds the thread 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 is entirely dependent on the maximum thread size that the operating system (or JVM) can create. The Synchronousqueue is a blocking queue with a buffer of 1.
4) Scheduledthreadpool: The core thread pool is fixed, and the size is unlimited. This thread pool supports the need to schedule and periodically perform tasks.
Public Static Executorservice newscheduledthreadpool (int corepoolsize) { returnnew Scheduledthreadpool (Corepoolsize, integer.max_value, default_keepalive_millis, MILLISECONDS, New delayedworkqueue ()); }
5. Principle of thread pool implementation
If only the use of the thread pool, then this blog is not much value, at best, is familiar with the process of executor related APIs. The thread pool implementation process does not use the Synchronized keyword, with volatile,lock and synchronous (blocking) queues, atomic related classes, Futuretask, and so on, because the latter performs better. The process of understanding can be very good to learn the idea of concurrency control in the source code.
The Threadpoolexecutor main worker class is used to control the reuse of threads. Look at the simplified code of the worker class, so it's easy to understand:
Private Final classWorkerImplementsRunnable {Finalthread thread; Runnable Firsttask; Worker (Runnable firsttask) { This. Firsttask =Firsttask; This. Thread = Getthreadfactory (). Newthread ( This); } Public voidrun () {Runworker ( This); } Final voidRunworker (Worker w) {Runnable task=W.firsttask; W.firsttask=NULL; while(Task! =NULL|| (Task = Gettask ())! =NULL) {task.run (); }}
The worker is a runnable and has a thread, which is the threading to be opened, creates a new thread object while creating a new worker object, and passes the worker itself as a parameter to the TThread. So when the start () method of the thread is called, it is actually the worker's run () method, and then to Runworker (), there is a while loop, which is executed sequentially from the Gettask () Runnable object. Gettask () How to get Runnable object?
Private Runnable Gettask () { if(some special case) { returnnull; } = Workqueue.take (); return R;}
This workqueue is the Blockingqueue queue that holds the task when the Threadpoolexecutor is initialized, and this queue is the runnable task that will be executed. Because Blockingqueue is a blocking queue, blockingqueue.take () gets into a wait state until Blockingqueue has a new object joined and wakes up the blocked thread if it is empty. So the general thread of the run () method will not end, but continue to carry out the runnable task from the Workqueue, which has reached the principle of thread reuse.
To control the maximum number of concurrent:
When was the runnable put into workqueue? When is the worker created, and when does the thread in the worker call Start () to open a new thread to execute the worker's run () method? The above analysis shows that the Runworker () in the worker is executed one after the other, serially, and how does concurrency manifest?
It is easy to think that some of the above tasks will be done when execute (Runnable Runnable). See how it's done in execute.
Public voidExecute (Runnable command) {if(Command = =NULL) Throw NewNullPointerException (); intc =Ctl.get (); //Current number of threads < Corepoolsize if(Workercountof (c) <corepoolsize) { //start a new thread directly. if(Addworker (Command,true)) return; C=Ctl.get (); } //number of active threads >= corepoolsize//runstate for running && queue not full//Workqueue.offer (command) represents the addition to the queue, or False if the add succeeds returning True if(IsRunning (c) &&workqueue.offer (command)) { intRecheck =Ctl.get (); //Check again for running status//the non-running state removes the task from the Workqueue and rejects if(!isrunning (Recheck) &&Remove (command)) reject (command);//reject a task with a policy specified by the thread pool//Two types of cases://1. Non-running status reject new task//2. Queue full start new thread failed (Workcount > Maximumpoolsize)}Else if(!addworker (Command,false) ) reject (command);}
Follow the code to see the additional tasks that are mentioned in the thread pool work process:
If the number of threads running is less than corepoolsize, then create the thread to run the task immediately;
If the number of threads running is greater than or equal to Corepoolsize, the task is placed in the queue;
If the queue is full and the number of threads running is less than maximumpoolsize, then create a non-core thread to run the task immediately;
If the queue is full and the number of threads running is greater than or equal to maximumpoolsize, the thread pool throws an exception rejectexecutionexception.
From Link: http://www.imooc.com/article/19226
Java thread pool related knowledge points summary