Multi-thread explanation for Android

Source: Internet
Author: User

There are several ways to use threads to process long-time "Businesses": 1) Activity. runOnUiThread (Runnable) 2) View. post (Runnable); View. postDelay (Runnable, long) 3) Handler 4) AsyncTask Android is a single-thread model. This means that Android UI operations are not thread-safe and must be executed in the UI thread, therefore, you cannot simply create a new Thread and start () because it violates the single-Thread model of Android. So how can we make good use of multithreading? Summary: The principle of event processing: all operations that may take time are processed by other threads. The Main thread event processing in Android cannot be too time-consuming. Otherwise, the subsequent events cannot receive a response within five seconds. the ANR dialog box is displayed. Which methods will be executed in the Main thread? 1) Activity lifecycle methods, such as onCreate (), onStart (), onResume (), etc. 2) event handling methods, such as onClick (), onItemClick () normally, the method starting with on in the Android base class is called back in the Main thread. To improve application responsiveness, you can start from these two aspects. Generally, the execution time of the onCreate (), onStart (), and onResume () Methods of the Activity determines the time when your application homepage is opened, try to put unnecessary operations in other threads for processing. If it is still time-consuming, you can use SplashScreen. It is best to use dynamic to use SplashScreen, so that the user knows that your application is not dead. When a user interacts with your application, the execution speed of the event processing method determines whether the application's responsiveness is good. It is generally divided into synchronous and asynchronous scenarios: 1) synchronization, wait for the returned results. For example, if a user clicks the register button and needs to wait for the server to return the result, a progress bar is required to prompt the user that your program is running and does not die. Generally, a progress bar is required for interaction with the server. For example, if the browser comes with the system, a progress bar is displayed during URL jump. 2) asynchronous. You do not need to wait for the returned results. For example, if you click the "add to Favorites" button in Weibo, you can just tell me if it is successfully executed. I don't want to wait for it. It is best to implement it asynchronously. Regardless of synchronous and asynchronous processing, event processing may be time-consuming. Therefore, you need to put it in other threads for processing. After the processing is complete, the interface will be notified to refresh. Note that not all interface refreshing behaviors need to be processed by the Main thread. For example, the setText () method of TextView must be in the Main thread; otherwise, CalledFromWrongThreadException will be thrown, the setProgress () method of ProgressBar does not need to be processed in the Main thread. Of course, you can also put all the UI component-related behaviors in the Main thread for processing, no problem. It can reduce the burden on your thinking, but you 'd better understand the differences between them and the experts who grasp the nuances between things. Put the event processing code in other threads for processing. If the processing result needs to be refreshed on the interface, the inter-thread communication method is required to send messages to the Main thread for processing in other threads. There are multiple ways to implement inter-thread communication in Android to implement communication between other threads and Main threads. Here we will introduce two common methods. 1) AsyncTask is an auxiliary class for asynchronous processing provided by the Android framework. It can perform time-consuming operations in other threads, and the processing result is executed in the Main thread. for developers, it shields the concept of multithreading and Handler to be discussed later. You don't know how to deal with inter-thread communication. AsyncTask helps you well. You will find that your code is easy to understand, because they all have some methods with specific responsibilities, especially AsyncTask, which has a preprocessing method onPreExecute, there are methods for executing tasks in the background, such as doInBackground, publishProgress for updating progress, onPostExecute for returning results, and so on. This is not like the methods for post, and all operations are written in a Runnable. But the better the encapsulation, the more advanced the API, the worse it is for junior programmers, that is, you do not understand its principles. When you need to deal with more complex situations, and advanced APIs cannot be done well, you will have a cup of cake. Therefore, we also need to master the more powerful functions and more free ways to communicate with the Main thread: the use of Handler. 2) use Handler. here you need to understand the classes of Inter-thread communication provided by the Android SDK. 2.1 Handler is responsible for sending and processing messages in android. It can implement message communication between other threads and Main threads. 2.2 loose logoff is responsible for managing the Message queues and Message loops of threads. 2.3 Message is the Message carrier for inter-thread communication. The Message serves as a container to store any messages you want to transmit between two terminals. 2.4 MessageQueue is a message queue. It is used to save messages to be processed by threads. The relationship between the four is that Handler is called in other threads. sendMsg () method (the parameter is a Message object). Add the events that need to be processed by the Main thread to the MessageQueue of the Main thread, when the Main thread extracts the Handler message from the Message Queue through mainlogoff, it calls back the handlerMessage () method of Handler. In addition to the above two common methods, there are also several simple methods 3) Activity. runOnUiThread (Runnable) 4) View. post (Runnable) View. postDelayed (Runnable, long) 5) Handler. post Handler. postDelayed (Runnable, long) uses the Thread pool to improve performance. Here we recommend that you use the Thread pool to manage temporary Thread objects to improve application performance. A thread pool is an instance of a resource pool in a thread application. Before learning about the thread pool, we should first understand the concept of the resource pool. In JAVA, creating and destroying objects consume resources. If we need to frequently create and destroy an object instance of a certain type in the application, many temporary objects will be generated. When there are too many temporary objects to be referenced, the virtual opportunity will be garbage collection (GC ), when the CPU is GC, the application may not run properly, resulting in reduced application responsiveness. The resource pool is used to solve this problem. When you need to use an object, you can obtain it from the resource pool. The resource pool is responsible for maintaining the object lifecycle. After learning about the resource pool, we will have a good understanding of the thread pool. The thread pool is the resource pool where all object types are stored in the thread. I have added an example of how to create Handler in other threads as an optional course. If you have mastered it, let's take a look. If you need to implement a message processing mechanism similar to that of the Main thread, other threads are required to communicate with your thread, which can be implemented in this way. 1. Question 1) Why multithreading is required? 2) How to Implement multithreading? 3) What is the core of the multithreading mechanism? 4) How many implementation methods are there? 2. Problem Analysis 1) The essence of Multithreading is asynchronous processing, which is simply not to make users feel "very stuck ". Eg: If you click the button to download a song and the button is pressed, the user experience will be poor. 2) multi-threaded implementation implements Runnable or extends Thread 3) multi-threaded core mechanism is Handler 4) provides the following implementation methods: Handler ------------ meaning 1. When creating a Handler, you must associate it with a logoff instance, the default constructor Handler () is the logoff method associated with the current Thread. Eg: we create a Handler in the UI Thread, and then we associate the Logoff of the UI Thread! This can be seen from the source code! The simplified code is as follows: public Handler () {mloler = Looper. myLooper (); // The Looper of the current thread. When the Activity is created, the UI thread has created a Looper object. // Looper is the core in the Handler mechanism, it keeps reading MessageQueue cyclically. if there is a Message to be processed, the Message is sent to the current Handler instance to process if (mLooper = null) {throw new RuntimeException ("Can't create handler inside thread that has not called logoff. prepare () ") ;}// as you can see above, a Handler instance must be associated with a logoff object; otherwise, mQueue = mloue. mQueue; // Handler Mes SageQueue, is it FIFO? No! I think it should be sorted by time! What is the relationship between Message and MessageQueue? If you are interested, you can study the source code! MCallback = null;} when creating a Handler, you can also specify the logoff. At this time, the logoff object can be the current thread or other threads! Handler only processes the Message in MessageQueue Of The logoff associated with it. As for the Logoff of the thread, Handler is not very concerned about it! Eg: we have created a Handler instance in the UI thread. At this time, it is passed to the Logoff of the Worker thread and can still perform business operations! Eg: -------------------- create the Worker thread private static final class Worker implements Runnable {private static final Object mLock = new Object (); private Looper mloments; public Worker (String name) {final Thread thread = new Thread (null, this, name); thread. setPriority (Thread. MIN_PRIORITY); thread. start (); synchronized (mLock) {while (mloiter = null) {try {mLock. wait ();} catch (InterruptedException E) {e. printStackTrace () ;}}}@ Override public void run () {synchronized (mLock) {// This method can only be executed once, and one Thread can only be associated with one Looper. prepare (); mloe = logoff. mylogoff (); mLock. policyall ();} logoff. loop ();} public Looper getLooper () {return mLooper;} public void quit () {mloit. quit () ;}} we can create a Handler in the UI thread and input the Looper eg: -------------- of the Worker to define our own Handler private final class MyHandler. Extends Handler {private long id; public MyHandler (loadeloader) {super (logoff) ;}@ Override public void handleMessage (Message msg) {switch (msg. what) {case 100: mTv. setText ("" + id); break ;}}--------- create Handler this in Activity. mWorker = new Worker ("workerThread"); this. mMyHandler = new MyHandler (this. mWorker. getLooper (); --------- create Message final Message msg = this. mMyHandler. obtain Message (100); msg. put ("test", "test"); msg. sendToTarget (); note that each Message must have its own Target, that is, the Handler instance! Source code: public final Message obtainMessage (int what) {return Message. obtain (this, what);} public static Message obtain (Handler h, int what) {Message m = obtain (); m.tar get = h; // The message is associated with the current Handler m. what = what; return m;} The above is just a theoretical explanation! Handler is usually used to handle Asynchronous interaction with multiple threads! Android requires that only the UI thread can update the user interface and accept user buttons and touch events! Therefore, you must ensure that the UI thread cannot be blocked, so that a new thread must be enabled for time-consuming operations! The problem arises. After the time-consuming operation is over, how can we report the latest data to users? However, we currently work in the Worker thread, so we cannot update the UI. So what should we do? You must pass the latest data to a place that can be processed by the UI thread! Now I am dispatched to Handler! What did Handler do? The following is a brief description: When the UI thread of the Activity is created, it is associated with logoff and MessageQueue. Then we create our own Handler in the UI thread, handler belongs to the UI thread, so it can interact with the UI thread! The logoff of the UI thread is always executing the Loop operation MessageQueue to read the conforming Message and send it to its target, that is, Handler! Therefore, we only need to put the latest data in the MessageQueue Of The logoff associated with Handler in the Worker thread. However, logoff is always in the loop operation. Once there is a Message that meets the requirements, the target of the Message is Handler! Therefore, when creating a Message, we should specify its target as Handler! But we can also, new Message () --> mHandler. sendMessage (msg); this is a special case! If we get the Message object through the obtainMessage () method, Handler will automatically set the target of the Message. Check the source code! To put it simply, the UI thread or Worker thread provides MessageQueue. Handler fills in the Message to it, and logoff reads the Message from it, and then submits it to the target of the Message, that is, Handler !! It is finally called from the handlmescript (Message msg) method of the Handler of the UI thread !! This is the core of multi-thread asynchronous processing in Android !! A little wordy !! **************************************** * ************************** Create Handler in the UI thread [generally inherit HandleMessage (Message msg )] | loop can belong to a UI thread or Worker thread | from the messgequeueof Loopers, Loopers directly operate on loop((get, and execute msg.tar get in loop(get get. dispatchMessage (msg); Call handleMessage (Message msg) of Handler | get Message in Worker thread, then pass in MessageQueue ************************************* through Handler *********************************** ********************************-------------- --- When creating a logoff, A MessageQueue private logoff () {mQueue = new MessageQueue (); mRun = true; mThread = Thread is created. currentThread () ;}---- 2 ----- View post (Runnable action) postDelay (Runnable action, long miliseconds) ----- 3 ----- Activity runOnUiThread (Runnable action) This method is easy to implement: public final void runOnUiThread (Runnable action) {if (Thread. currentThread ()! = MUiThread) {// if the current thread is not the UI thread mHandler. post (action);} else {action. run () ;}among them: mUiThread = Thread. currentThread (); mHandler = new Handler () ----- 4 ----- AsyncTask <Params, Progress, Result> Params, Progress, and Result are all data types, the type of the data to be processed by Params. The Result returned after the Result of the Progress type is processed by Progress is a simple method of asynchronous processing! Method execution sequence: 1) onPreExecute () -- execute in the UI thread and perform some initialization operations. 2) doInBackground (Params... params) -- execute in the Worker thread for time-consuming background processing. In this method, you can call publishProgress (Progress progress) for Progress processing. 3) onProgressUpdate (progress Progress) -- execute in UI thread and process progress in real time 4) onPostExecute (Result result) -- execute in UI thread, in doInBackground (Params... params) after return, call 5) onCancelled () -- execute in the UI thread and execute it after the AsyncTask instance calls the cancle (true) method. Pay attention to some cleaning operations: asyncTask must be created in the UI thread, asyn CTask.exe cute (Params... params); executed in the UI thread, and can only be executed once. To call execute (Params... params), you must recreate the AsyncTask object. The last three methods are implemented by Handler!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.