As developers, we all know that it is unavoidable to encounter time-consuming operations in the development process, such as network requests, file reads and writes, database operations, and so on. Android is a single-threaded model, which means that Android UI operations are not thread-safe and that these actions must be performed in the UI thread. But Android also made a time limit on UI operations, Activity--> 5s, Broadcastreceiver/contentprovider--> 10s, service--> 20s, over which A time will be reported to ANR. So in order to avoid the ANR, we will open up new threads to do these operations. For a new thread, if you're still doing it through new thread, I think it's going to change. Do not say such a way to the memory, the consumption of resources, some models are open to an application of the number of threads is limited, over the over. So it's important to look at the multi-threaded operations in Android for these situations. Android provides four common ways to operate multithreading, respectively:
1. Handler+thread
2. Asynctask
3. Threadpoolexecutor
4. Intentservice 1. The Handler+thread 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 messages queue, and the Looper is responsible for managing the thread's message queue and message loop, and then processing 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. Callback Handler's Handlermessage () method. So the handler process, the key role: MessageQueue, Looper, message/runnable.
Advantages and Disadvantages
1. Handler用法简单明了,可以将多个异步任务更新UI的代码放在一起,清晰明了2. 处理单个异步任务代码略显多
Scope of application:
1. 多个异步任务的更新UI
2. Asynctask Asynctask stores pending tasks through a blocking queue blockingquery<runnable>, using a static thread pool Thread_pool_executor 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. Take a look at the sample code:
classDownloadtaskextendsAsynctask<integer, Integer, string> {
//Asynctask<params, Progress, result>//in the back angle brackets are the parameters respectively@Overrideprotected voidOnPreExecute () {//The first method of execution Super. OnPreExecute (); } @OverrideprotectedString doinbackground (Integer ... params) {
//second Execution method, OnPreExecute () executes after executionreturn"Execution Complete"; } @Overrideprotected voidOnprogressupdate (Integer ... progress) {
//Show ProgressSuper. Onprogressupdate (progress); } @Overrideprotected voidOnPostExecute (String result) {
//Doinbackground is triggered when the return is returned, in other words, doinbackground after execution is completed.Super. OnPostExecute (Result); } }
With the sample code, we know several important methods of Asynctask: OnPreExecute (), Doinbackground (integer ... params), Onprogressupdate (integer ... Progress), OnPostExecute (String result). In these four methods, Onprogressupdate is not triggered by default and needs to be called by the object Publishprogress () method.
Advantages and Disadvantages
1. 处理单个异步任务简单,可以获取到异步任务的进度
2. 可以通过cancel方法取消还没执行完的AsyncTask
3. 处理多个异步任务代码显得较多
Scope of application:
1. 单个异步任务的处理
3. 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. However, we do not allow the use of executor to create a thread pool here, but rather to avoid the risk of resource exhaustion by Threadpoolexcutor.
Description
1) Fixedthreadpool and Singlethreadpool: The allowable request queue Length is integer.max_value, which may accumulate a large number of requests, resulting in OOM;
2) Cachedthreadpool and Scheduledthreadpool: The number of threads allowed to create is integer.max_value, which may create a large number of threads, resulting in OOM.
So the right way: (More detailed development specifications, click here)
int Number_of_cores = runtime.getruntime (). Availableprocessors (); int Keep_alive_time = 1= timeunit.seconds; BlockingqueueNew linkedblockingqueue<runnable>new New New Defaultrejectedexecutionhandler ());
Scope of application
1. 批处理任务
4. Intentserviceintentservice inherits from service and is a packaged lightweight service that is 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. Avoid time-consuming operations in broadcastreceiver#onreceive (), and if there is a time-consuming operation, you should create a intentservice complete instead of creating a child thread within the broadcastreceiver.
Characteristics
1. 一个可以处理异步任务的简单Service
Reference:
Https://www.jianshu.com/p/2b634a7c49ec
Https://www.cnblogs.com/chendu123/p/6081301.html
Android multithreaded model