Android development art Exploration Study Notes (11), android art Exploration
Chapter 2 Android threads and thread pools
In terms of usage, threads are divided into subthreads and main threads. The main thread mainly processes interface-related things, And subthreads are often used to execute time-consuming operations. AsyncTask, IntentService, and HandlerThread can all play the role of a thread.
AsyncTask encapsulates the thread pool and Handler to facilitate developers to update the UI in the main thread.
HandlerThread is a thread with a message loop and can be used inside it.
IntentService is a service that is encapsulated by the system to facilitate the execution of background tasks. IntentService uses HandlerThread internally to execute tasks, after the task is completed, IntentService automatically exits. Because of its high priority, it is not easy to be killed by the system.
11.1 main thread and subthread
Main thread-process interface Interaction Related logic, run four major components and process their interaction with users.
Sub-thread-Execute time-consuming tasks, such as network requests and IO operations. (Network access from 3.0 cannot be in the main thread, otherwise NetworkOnMainThreadException)
11.2 thread form in Android
11.2.1 AsyncTask
A lightweight asynchronous task class that executes background tasks in an online City pool, then transmits the health of execution and final results to the main thread, and updates the UI in the main thread, it is not recommended to run tasks that are particularly time-consuming.
Class declaration:
public abstract class AsyncTask<Params,Progress,Result>
Params: parameter type;
Progress: Background task execution Progress type;
Result: The type of the Result returned by the background task.
If you do not need to pass the preceding parameters, you can use Void instead.
Four core methods:
(1) onPreExecute () -- initialization preparation, which is executed in the main thread;
(2) doInBackground (Params... params) -- executes asynchronous tasks and threads in the thread pool. During execution, the publishProgress method is used to update the task progress. The publishProgress method triggers onProgressUpdate ();
(3) onProgressUpdate (Progress... values) -- Update the task Progress, which is executed in the main thread.
(4) onPostExecute (Result result) -- The Result returned by the asynchronous task is executed by the main thread.
Note:... in java, the parameters are not fixed. array parameters.
To execute an asynchronous task, follow these steps:
new MyAsyncTask().execute(url1,url2,url3);
Limitations of AsyncTask:
(1) The AsyncTask class must be loaded in the main thread (default );
(2) The AsyncTask object must be created in the main thread;
(3) The execute method must be called in the main thread;
(4) do not directly call four core methods;
(5) An AsyncTask object can only be executed once, that is, the execute method can only be called once. Otherwise, an exception occurs during running.
11.2.3 HandlerThread
HandlerThread inherits from Thread, which is a kind of Thread that can use handler. The specific use case is IntentService.
11.2.4 IntentService
IntentService is a special Service that encapsulates HandlerThread and Handler. It is used to execute time-consuming tasks in the background and stops tasks automatically after execution. It is more suitable for executing background tasks with higher priorities.
11.3 thread pool in Android
Advantages of thread pool:
(1) reusing threads in the thread pool can reduce performance overhead;
(2) It can effectively control the maximum number of concurrent threads in the thread pool and avoid blocking between a large number of threads due to mutual preemption of system resources.
(3) simple management of threads, regular execution, and specified interval loop execution.
The thread pool in Android is implemented directly or indirectly by configuring ThreadPoolExecute.
11.3.1 ThreadPoolExecute
Thread Pool Construction Method:
public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TileUnit unit,BlockingQueue<Runnable> workQueue,THreadFactory threadFactory)
CorePoolSize: number of core threads;
MaximumPoolSize: Maximum number of threads;
KeepAliveTime: the timeout duration of idle non-core threads;
Unit: The time unit of keepAliveTime, such as TimeUnit. MILLISECONDS (MILLISECONDS), TimeUnit. SECONDS (SECONDS), TimeUnit. MINUTES (MINUTES)
WorkQueue: The task queue in the thread pool.
ThreadFactory: A thread factory used to create a thread for a thread pool.
11.3.2 classification of thread pools
(1) FixedThreadPool-only core threads;
(2) CachedThreadPool-only non-core threads, suitable for executing a large number of tasks that consume less time;
(3) ScheduledThreadPool-the number of core threads is fixed, and the number of non-core threads is unlimited. It is used to execute scheduled tasks and repeat tasks with a fixed cycle;
(4) SingleThreadExecutor-there is only one core thread to solve the thread synchronization problem.