Threading is an important concept in Android, where threads are divided into the main thread and sub-threads, and the primary thread is primarily about interface-related things, while child threads are often used for time-consuming operations. Due to the features of Android, it is easy to make the program unable to respond in time if the time-consuming operation is performed in the main thread. In addition to the thread itself, there are many more things that can play a threading role in Android, such as:
Asynctask,intentservice and Handlerthread. Different forms of threads are threads, but they still have different features and usage scenarios.
11.1 Main thread and child thread
The main thread is the threads owned by the process, and in Java by default a process has only one thread, which is the main thread. The main thread handles interface interaction related logic, because the user can interact with the interface at any time, so the main thread must have a high response speed at all times, otherwise it will create a feeling of the interface lag. In order to maintain a high response speed, this requires that the main thread cannot perform time-consuming operations, which is where the child threads come in handy.
11.2 Threading Patterns in Android
11.2.1 Asynctask
Asynctask is a lightweight asynchronous task class that can perform background tasks in a thread pool and then pass the progress of execution and the results of execution to the main thread and update the UI in the main thread. From the implementation, Asynctask encapsulates thread and handler, which makes it easier to perform background tasks and access the UI in the main thread through Asynctask.
Asynctask is an abstract generic class that provides the three generic parameters of params, progress, and result. where params represents the type of the parameter, progress represents the type of background task execution progress, and result indicates the type of return result of the background task.
Asynctask provides 4 core methods, and their meaning is not spoken. Here is just a simple mention.
(1) OnPreExecute: Executed in the main thread, this method is called before the asynchronous task executes
(2) Doinbackground (params...params): Executed in the thread pool, this method is used to perform asynchronous tasks, and the Params parameter represents the input parameters of the asynchronous task. In this method, the task progress can be updated by the Publishprogress method, and the Publishprogress method will callback the Onprogressupdate method. In addition, this method needs to return the result of the calculation to OnPostExecute
(3) Onprogressupdate (progress...values): Executed in the main thread, this method is called when the execution progress of the acquired task changes
(4) OnPostExecute (result result): Called after the asynchronous task has finished executing
Asynctask in the use of the process still have some restrictions, the main points are as follows:
(1) Asynctask class must be loaded in the main thread, which means that the first access to Asynctask must occur in the main thread, of course, the process in Android4.1 and above has been automatically completed by the system. In the main method of Activitythread, it invokes the Init method of Asynctask, which satisfies the condition that the Asynctask class must be preempted on the main line.
(2) The Asynctask object must be created in the main thread
(3) The Execute method must be called in the UI thread
(4) Do not call 4 core methods directly in the program
(5) A Asynctask object can only be executed once, that is, the Execute method can only be called once
(6) Asynctask default is to invoke the Execute method to perform the task serially, but we can still invoke the Executeonexecutor method to execute in parallel
How the 11.2.2 Asynctask works
The principle of its implementation is this:
The Execute method is executed on the main thread. This method calls the OnPreExecute method and then encapsulates the params parameter into a Futuretask "inherited from Runnable" to Serialexecutor "Queued for Tasks" Execute method to handle, The Execute method adds the Futuretask object to the task queue to wait for Thread_pool_executor to perform the task, and once the executive officer calls the Doinbackground method,
1) In this user-replicated method, if the Publishprocess method is called, a message_post_progress message is sent through Asynctask's inner class Internalhandler instance Shandler, updating the progress, Shandler onprogressupdate (Progress ... values) method will be called when processing messages;
2) If an exception is encountered during execution, a MESSAGE_POST_CANCEL message is sent, the task is canceled, and the Oncancelled () method is called when Shandler processes the message;
3) If the execution succeeds, a message_post_result message is sent, the result is displayed, and the OnPostExecute (result result) method is called when Shandler processes the message;
There are two thread pools (Serialexecutor and Thread_pool_executor) and a static handler (Internalhandler) in Asynctask, where the thread pool Serialexecutor is used for task queuing While the thread pool thread_pool_executor is used for real task execution, Handler (Internalhandler) is used to switch the working environment in the main thread.
An Internalhandler instance that inherits from Handler Shandler is a static handler object that must be required to be created in the main thread in order to be able to switch the execution environment to the main thread. And because Shandler is static, it is initialized when the class is loaded. In general, the Asynctask class must be loaded in the main thread.
11.2.3 Handlerthread
She inherits thread, a thread that can use handler to "think of itself as containing Looper". It creates the message queue through Looper.prepare () in the Run method and opens the message loop through Looper.loop (), allowing handler to be created in Handlerthread in the actual use.
Use steps
Although Handlerthread's documentation is relatively simple, its use is not as easy as it might seem.
Let's take a look at its use steps:
(1) Create a handlerthread that creates a thread that contains looper.
new HandlerThread("leochin.com"//创建HandlerThread后一定要记得start()
(2) Get Handlerthread's Looper
Looper looper = handlerThread.getLooper();
(3) Create handler, initialize by Looper
Handler handler = new Handler(looper);
Next you can send messages to the worker thread through handler. Finally note that because the Handlerthread run method is an infinite loop, it is a good programming practice to terminate the execution of a thread by its quit or quitsafely method when it is clear that it is not necessary to use Handlerthread.
11.2.4 Intentservice
is a special service that inherits the service and it is an abstract class, so you must create its subclasses to use Intentservice. Intentservice can be used to perform time-consuming tasks in the background.
Advantages:
(1) It will stop automatically when the task is executed.
(2) Because of the characteristics of the service, so it has a higher priority than the normal thread is not easy to be killed in the background,
The Intentservice encapsulates Handlerthread and handler. This can be seen from the OnCreate method:
publicvoidonCreate() { super.onCreate(); new HandlerThread("IntentService[""]"); thread.start(); mServiceLooper = thread.getLooper(); new ServiceHandler(mServiceLooper); }
As you can see, the Handlerthread object is created in the OnCreate method and the thread is opened. This thread takes the Looper object and then uploads the Looper object as a parameter to handler to create a Mservicehandler object. Each time you start Intentservice, the OnStart method is called, and in this method Intentservice only sends a message through Mservicehandler, which is handled in Handlerthread. Here is the source code for OnStart:
publicvoidonStartint startId) { Message msg = mServiceHandler.obtainMessage(); msg.arg1 = startId; msg.obj = intent; mServiceHandler.sendMessage(msg); }
The above servicehandler is an inner class of Intentservice, which inherits handler. As shown below:
privatefinalclass ServiceHandler extends Handler { publicServiceHandler(Looper looper) { super(looper); } publicvoidhandleMessage(Message msg) { onHandleIntent((Intent)msg.obj); stopSelf(msg.arg1); } }
The above sends a message in the OnStart method, and finally invokes the Onhandlerintent method that the user needs to overwrite in the Mservicehandler Handlemessage method to handle the message. Call Stopself (MSG.ARG1) to stop the service after the last message has been processed.
11.3 Thread Pool
Referring to the thread pool it is necessary to say the benefits of a thread pool:
(1) Reusing threads to avoid the performance overhead caused by frequent creation and destruction of threads;
(2) Can effectively control the maximum number of threads in the thread pool, to avoid the congestion caused by a large number of threading between the resources;
(3) can be simple management of the thread;
The concept of the thread pool in Android comes from the Executor,executor in Java is an interface, and the real thread pool implementation is threadpoolexecutor. Threadpoolexecutor provides a range of parameters to configure. You can create different thread pools with different configurations. From the functional features of the thread pool, the thread pools of Android are mainly divided into 4 categories, which can be obtained through the factory method provided by executors. We can take a look at Threadpoolexecutor first.
11.3.1 Threadpoolexecutor
Threadpoolexecutor is the real implementation of the thread pool, and its construction method provides a set of parameters to configure the thread pool:
public Threadpoolexecutor (int corepoolsize, int maximumpoolsize, long KeepAliveTime, Timeunit unit, blockingqueue<runnable> WorkQueue, Threadfactory threadfactory) {this (Corepoolsize, Maximumpo Olsize, KeepAliveTime, Unit, WorkQueue, Threadfactory, DefaultHandler); }
(1) Corepoolsize: The number of core threads in the thread pool. By default, the core threads will survive in the thread pool even if they are in an idle state. However, if the allowcorethreadtimeout in Threadpoolexecutor is set to true, the idle core thread will have a timeout policy waiting for the new task to arrive. This time interval is specified by KeepAliveTime. The core thread is terminated when the wait time exceeds the time specified by KeepAliveTime.
(2) Maximumpoolsize: The maximum number of threads that the thread pool can hold, and when the number of active threads reaches this value, subsequent new tasks are blocked.
(3) KeepAliveTime: The timeout length of idle threads.
(4) Unit: The unit of time used to specify the KeepAliveTime parameter.
(5) WorkQueue: The thread pool's task queue, which is stored by Runnable objects submitted through the Threadpoolexecutor Execute method.
(6) Threadfactory: Thread factory, the ability to create new threads for the thread pool.
Threadpoolexecutor The following rules are generally followed when performing a task:
(1) If the number of threads in the thread pool does not reach the number of core threads, then a new task will create a new core thread;
(2) If the number of threads in the thread pool reaches or exceeds the number of core threads, the new task is added to the wait queue;
(3) If the waiting queue is full, but the number of threads does not reach the maximum number of threads, a non-core thread is started to perform the task;
(4) If the number of threads in step 3 has reached the maximum specified by the thread pool, then the task is rejected and an exception is thrown;
The parameter configuration of Threadpoolexecutor is obvious in Asynctask, the following is the configuration of the thread pool in asynctask;
Private Static FinalString Log_tag ="Asynctask";Private Static Final intCpu_count = Runtime.getruntime (). Availableprocessors ();Private Static Final intCore_pool_size = Cpu_count +1;Private Static Final intMaximum_pool_size = Cpu_count *2+1;Private Static Final intKeep_alive =1;Private Static FinalThreadfactory sthreadfactory =NewThreadfactory () {Private FinalAtomicinteger MCount =NewAtomicinteger (1); PublicThreadNewthread(Runnable R) {return NewThread (R,"Asynctask #"+ mcount.getandincrement ()); } };Private Static FinalBlockingqueue<runnable> Spoolworkqueue =NewLinkedblockingqueue<runnable> ( -); Public Static FinalExecutor Thread_pool_executor =NewThreadpoolexecutor (Core_pool_size, Maximum_pool_size, Keep_alive, Timeunit. SECONDS, sthreadfactory);
11.3. Classification of 2 thread pools
1,fixthreadpool
It's a thread pool with a fixed number of threads, and it's all core threads. Threads are idle and will not be recycled unless the thread pool is closed. When all the threads are active, the new task waits until an idle thread comes out. Because of its remarkable characteristics, this means that it can respond to external requests more quickly. In addition the task queue is also no size limit.
2,cachethreadpool
is a thread pool in which the number of threads is not fixed. It has only non-core threads, and its maximum number of threads is integer.max_value. Since this is a large number, you can assume that the maximum number of threads can be arbitrarily large. When there are idle threads in the thread pool, a new task is performed with the idle thread, but the idle thread is a time-limited "60s", and when there is no idle thread, a new thread is created to perform the new task. It is also worth noting that the task queue for this thread pool is actually equivalent to an empty collection. This means that new tasks are immediately executed without waiting. This type of thread pool is better suited to perform a large number of less time-consuming tasks.
3,schemethreadpool
The number of core threads is fixed, but the number of non-core threads is unlimited and is immediately recycled when non-core threads are idle. This type of thread pool is used to perform timed tasks and repetitive tasks with fixed periods.
4,singlethreadpool
There is only one core thread, and the tasks are executed sequentially in the same thread. Its meaning is to unify all the outside tasks into one thread, which makes it unnecessary to handle thread synchronization between these tasks.
Chapter 11th Android threads and thread pools