When we launch an app, the Android system launches a Linux processthat contains a Thread called the UI thread or the main thread. Usually all components of an application run in this process, and of course you can modify the blocks of code in the Manifest.xml by modifying the four components (<activity><service><provider the android:process property in ><receiver> specifies that it runs in a different process . When a component is started, if the process already exists, the component is started directly through the process and runs in the UI thread of the process.
The UI thread runs a number of important logic, such as system event handling, user input event handling, UI drawing, Service,alarm, etc., such as:
The logic contained in the UI thread
The code we write is interspersed in the middle of these logic, such as the detection and response of user touch events, the processing of user input, custom view rendering, and so on. If the code we insert is time-consuming, such as a network request or database read, it blocks the execution of other logic on the UI thread, causing the interface to stutter. If the lag time is longer than 5 seconds, the system will report a ANR error. So, if we're going to take a time-consuming operation, we need another thread to execute.
After a new thread executes the time-consuming logic, it often needs to feed the results back to the interface for UI updates. The Android UI toolkit is not thread-safe and cannot be updated in the UI by non-UI threads, and all updates to the interface must be made on the UI thread.
Android provides four common ways to operate multithreading, respectively:
1. Handler+Thread2. AsyncTask3. ThreadPoolExecutor4. IntentService
The following distributions are presented in four ways
Handler+thread
The Android main thread contains a message queue (MessageQueue) that can be stored in a series of message or Runnable objects. With a handler you can send a message or Runnable object to this queue and process the objects. Each time you create a new handle object, it is bound to the thread that created it (that is, the UI thread) and the thread's message queue, and from that point on, the handler begins to pass the message or Runnable object to the queue and execute them when they are out of the queue.
Handler thread schematic diagram
Handler can put a message object or Runnable object into the message queue, in order to get a message in the UI thread or execute the Runnable object, handler to press into the message queue there are two kinds of ways, Post and SendMessage:
Post mode:
Post allows a Runnable object to be enqueued into the message queue. It has the following methods:
Post (Runnable)/postattime (Runnable,long)/postdelayed (Runnable,long)
For Handler post, it passes a Runnable object to the message queue, and in this Runnable object, rewrite the run () method. In this run () method, it is common to write operations that need to be on the UI thread.
Handler Post usage
SendMessage:
SendMessage allows a Message object containing the message data to be pressed into the queue of messages. It has the following methods:
Sendemptymessage (int)/sendmessage (Message)/sendmessageattime (Message,long)/sendmessagedelayed (Message,long)
Handler if you are using SendMessage to enqueue messages into a message queue, you need to pass a message object, and in handler, you need to override the Handlemessage () method to get the message that the work line path pass. This method runs on the UI thread. The message is a final class, so it cannot be inherited.
Pros and cons
1. Handler用法简单明了,可以将多个异步任务更新UI的代码放在一起,清晰明了2. 处理单个异步任务代码略显多
Scope of application
1. 多个异步任务的更新UI
Asynctask
Asynctask is a lightweight asynchronous class provided by Android that can inherit Asynctask directly, implement asynchronous operations in a class, and provide interface feedback about the current level of asynchronous execution (UI progress updates can be implemented through an interface), and finally feedback the execution results to the UI main thread.
Asynctask stores pending tasks through a blocking queue blockingquery<runnable>, using a static thread pool thread_pool_executor to provide a certain number of threads, by default 128. Prior to Android 3.0, the default is to take a parallel task executor, 3.0 later changed to a serial task executor by default, through the static serial task Executor Serial_executor control task serial execution, loop out the task to Thread_pool_ The thread in the executor executes, executes one, and then executes the next.
Examples of usage:
Class Downloadtask extends Asynctask<integer, Integer, string>{ //Asynctask<params, Progress, result> //The following angle brackets are arguments (in the example, thread breaks), progress (publishprogress used), return value type @Override protected void OnPreExecute () { //First execution method super.onpreex Ecute (); &NBSP;} @Override protected String doinbackground (Integer ... params) { &nbs P //second Execution method, OnPreExecute () executes after execution for (int i=0;i<=100;i++) { publishprogress (i); try { thread.sleep (params[ 0]); } catch (Interruptedexception e) { &NBS P e.printstacktrace (); } }   return "Execution Complete"; &NBSP;} @Override protected void Onprogressupdate (Integer ... progress) { &N Bsp //This function is triggered when Doinbackground calls Publishprogress, although only one parameter is called //But here is an array, so use progesss [0] to value //nth parameter is used Progress[n] to take the value tv.settext (progress[0]+ "%"); super.onprogressupdate (progress); &NBSP;} @Override protected void OnPostExecute (String result) { &NBS P;//doinbackground trigger on return, in other words, doinbackground after execution // The result here is the return value of the above doinbackground execution, so this is "done" settitle (result); super.onpostexecute (result); }}
Pros and cons
1. 处理单个异步任务简单,可以获取到异步任务的进度2. 可以通过cancel方法取消还没执行完的AsyncTask3. 处理多个异步任务代码显得较多
Scope of application
1. 单个异步任务的处理
Threadpoolexecutor
Threadpoolexecutor provides a set of thread pools that can manage multiple threads executing in parallel. This reduces the overhead of having each parallel task build threads on its own, and on the other hand manages the common resources of multiple concurrent threads, improving the efficiency of multithreading. So threadpoolexecutor is more suitable for the execution of a group of tasks. Executors uses the Factory mode to encapsulate the Threadpoolexecutor, which is more convenient to use.
Executors provides four ways to create Executorservice, with the following scenarios:
1. Executors.newCachedThreadPool() 创建一个定长的线程池,每提交一个任务就创建一个线程,直到达到池的最大长度,这时线程池会保持长度不再变化2. Executors.newFixedThreadPool() 创建一个可缓存的线程池,如果当前线程池的长度超过了处理的需要时,它可以灵活的回收空闲的线程,当需要增加时, 它可以灵活的添加新的线程,而不会对池的长度作任何限制3. Executors.newScheduledThreadPool() 创建一个定长的线程池,而且支持定时的以及周期性的任务执行,类似于Timer4. Executors.newSingleThreadExecutor() 创建一个单线程化的executor,它只创建唯一的worker线程来执行任务
Scope of application
1. 批处理任务
Intentservice
Intentservice inherits from service and is a packaged lightweight service used to receive and process asynchronous requests passed through intent. The client initiates a intentservice by calling StartService (Intent), which takes the order of a work thread sequentially and ends the service automatically after processing is complete.
features
1. 一个可以处理异步任务的简单Service
Four ways to use multi-threading in Android most fully summarized