<span id="Label3"></p>Basic introduction<p><p>The asynchronous message processing thread refers to a thread that enters a wireless loop body after it is started, does not loop once, pulls a message from the internal message queue, and calls back the corresponding message handler, and then resumes the loop after executing a message. If the message queue is empty, the thread pauses to know that there are new messages in the message Queue.<br>The asynchronous message processing thread is still essentially a thread, except that the Thread's execution code is set to the logic described Above. Implementing an asynchronous thread in Android involves several classes: threadlocal,looper,messagequeue,handler,message, which we'll look at in a couple of categories to resolve the asynchronous threading mechanism of ANDROID.<br>first, A Frame chart:<br></p></p>ThreadLocal<p><p>Threadlocal is not a class in the SDK of android, but a class in java.lang, which is a class that creates a thread-based variable store for threads, which we can call Thread-local Storage. Threadlocal can enable an object to be thread-isolated, maintaining its own copy of the variable for each thread, and binding the variable to the thread by its set Method. Threadlocal provides a solution to the problem of multithreading synchronization by copying each of the variables so that each thread operates on its own variables rather than a common one, so there is no need to synchronize Locks. To give a chestnut, we create a variable that is manipulated by two THREADS. In general, we will lock this variable and solve the problem of synchronization in this way. But when we use threaloca, we can make a copy of each thread through threadloca, and the copy is bound to the thread, which means that each thread can change its own variable without affecting another thread. So there's no need for a lock. Threadlocal is automatically bound to the current thread when set, without having to bind Itself. The code is not written here, the central idea is Ok. One might ask, what does this have to do with android? This is about our looper, because in the asynchronous thread of android, the thread variable that threadlocal binds to is an object of Looper.</p></p>Looper<p><p>What's the use of looper? to implement an asynchronous thread, you must looper, because Looper is used to generate a Messagequeue. We can see from the source code that there is a member variable Mqueue (an instance of the MessageQueue Class) in the Looper class that holds MessageQueue in Looper.<br>Looper creates a MessageQueue object by using the static method Looper.prepare () Method. Note that the Looper.prepare () method can only be executed once in a Thread.</p></p>Prepare () method<p><p>View Source Code:</p></p><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs cs"><span class="hljs-keyword">private</span><span class="hljs-keyword">static</span><span class="hljs-keyword">void</span><span class="hljs-title">prepare</span>(boolean quitAllowed) { <span class="hljs-keyword">if</span> (sThreadLocal.<span class="hljs-keyword">get</span><span class="hljs-keyword">null</span>) { <span class="hljs-keyword">throw</span><span class="hljs-keyword">new</span> RuntimeException(<span class="hljs-string">"Only one Looper may be created per thread"</span>); } sThreadLocal.<span class="hljs-keyword">set</span>(<span class="hljs-keyword">new</span> Looper(quitAllowed)); }</code></pre></pre><p><p>The above is the Android source code, executed two times prepare, will throw an Exception. This is actually very natural to think, because previously mentioned, looper is used to create Messagequeue. A thread can have only one messagequeue, so naturally there can be only one looper Object. Read prepare () Source code does not seem to have found that it created an instance of MessageQueue ah, right, here is not see, But. Let's take a look at the work done when creating a new Looper object:<br>We found the Looper constructor:</p></p><pre class="prettyprint"><pre class="prettyprint"><code class=" hljs java"> <span class="hljs-keyword">private</span><span class="hljs-title">Looper</span>(<span class="hljs-keyword">boolean</span> quitAllowed) { <span class="hljs-keyword">new</span> MessageQueue(quitAllowed); <span class="hljs-keyword">true</span>; mThread = Thread.currentThread(); }</code></pre></pre><p><p>We can see that this constructor of Looper is private, and Looper only has this Constructor. So we can see that we can't make a new Looper object in another class. But That's not the point, but the point is that Looper created a MessageQueue object Here.</p></p>Loop () method<p><p>Loop static method is used to perform the looping of the Message. Everyone should know that this is a dead loop. Used to continuously read messages in the message Team. Let's look at the source code: the source code is as Follows:</p></p><pre class="prettyprint"><code class=" hljs java"> <span class="hljs-keyword"><span class="hljs-keyword"></span> public</span> <span class="hljs-keyword"><span class="hljs-keyword">Static</span></span> <span class="hljs-keyword"><span class="hljs-keyword">void</span></span> <span class="hljs-title"><span class="hljs-title">Loop</span></span>() {<span class="hljs-keyword"><span class="hljs-keyword">Final</span></span>Looper me = Mylooper ();<span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(me = =<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>) {<span class="hljs-keyword"><span class="hljs-keyword">Throw</span></span> <span class="hljs-keyword"><span class="hljs-keyword">New</span></span>RuntimeException (<span class="hljs-string"><span class="hljs-string">"No Looper; Looper.prepare () wasn ' t called on the This Thread. "</span></span>); }<span class="hljs-keyword"><span class="hljs-keyword">Final</span></span>MessageQueue queue = me.mqueue;<span class="hljs-comment"><span class="hljs-comment">//make sure the identity of this thread is the the local process,</span></span> <span class="hljs-comment"><span class="hljs-comment">//and Keep</span> track of the what, identity token actually is.</span>Binder.clearcallingidentity ();<span class="hljs-keyword"><span class="hljs-keyword">Final</span></span> <span class="hljs-keyword"><span class="hljs-keyword">Long</span></span>Ident = Binder.clearcallingidentity ();<span class="hljs-keyword"><span class="hljs-keyword"></span> for</span>(;;) {Message msg = Queue.next ();<span class="hljs-comment"><span class="hljs-comment">//might Block</span></span> <span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(msg = =<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>) {<span class="hljs-comment"><span class="hljs-comment">//No message indicates that the message queue is Quitting.</span></span> <span class="hljs-keyword"><span class="hljs-keyword">return</span></span>; }<span class="hljs-comment"><span class="hljs-comment">//this must is in a local variable, with case a UI event sets the logger</span></span>Printer logging = me.mlogging;<span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(logging! =<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>) {logging.println (<span class="hljs-string"><span class="hljs-string">">>>>> dispatching to"</span></span>+ Msg.target +<span class="hljs-string"><span class="hljs-string">" "</span></span>+ Msg.callback +<span class="hljs-string"><span class="hljs-string">": "</span></span>+ msg.what); } msg.target.dispatchMessage (msg);<span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(logging! =<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>) {logging.println (<span class="hljs-string"><span class="hljs-string">"<<<<< finished to"</span></span>+ Msg.target +<span class="hljs-string"><span class="hljs-string">" "</span></span>+ msg.callback); }<span class="hljs-comment"><span class="hljs-comment">//make sure that during the course of dispatching</span> the</span> <span class="hljs-comment"><span class="hljs-comment">//identity of the thread wasn ' t Corrupted.</span></span> <span class="hljs-keyword"><span class="hljs-keyword">Final</span></span> <span class="hljs-keyword"><span class="hljs-keyword">Long</span></span>Newident = binder.clearcallingidentity ();<span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(ident! = Newident) {LOG.WTF (TAG,<span class="hljs-string"><span class="hljs-string">"Thread identity changed from 0x"</span></span>+ long.tohexstring (ident) +<span class="hljs-string"><span class="hljs-string">"to 0x"</span></span>+ long.tohexstring (newident) +<span class="hljs-string"><span class="hljs-string">"while dispatching to"</span></span>+ Msg.target.getClass (). getName () +<span class="hljs-string"><span class="hljs-string">" "</span></span>+ Msg.callback +<span class="hljs-string"><span class="hljs-string">"what="</span></span>+ msg.what); } msg.recycle (); } }</code></pre><p><p>The function mylooper is used to return the Looper object of the current thread through a for (;;) To execute the Loop. Inside the for loop, through the next method of MessageQueue to get out of the message, here is a point to note, is to take out the message, and finally call Msg.target.dispatchMessage (msg); To process the message, the method is in handler, because Msg.target is a handler object. Put it in the Handler.</p></p>MessageQueue<p><p>The MessageQueue is used to process message Queues. There are several methods in this class, one is the next () method, which is used to remove the next element in the Queue. Another is the Enqueuemessage method, which is used to add an element to the message Team. This method will be used in the SendMessage in handler, a little mention here, in Handler's sendmessage, This method is called to add the message to the MessageQueue of the receiving THREAD.</p></p>Handler<p><p>Handler is used to send information, the method we know is the SendMessage method, which is used to send messages to the message receiving THREAD. As stated in the above frame diagram, handler must be created in the thread that receives the message, so that the message can be sent to the Thread. Because the created handler object handler must have MessageQueue Message Queuing for that thread to send a message to that Thread. When handler is created, it uses the following constructor:</p></p>The handler constructor<pre class="prettyprint"><code class=" hljs handlebars"><span class="xml"><span class="hljs-tag"><span class="php"><span class="hljs-keyword"><span class="hljs-keyword"></span> public</span>Handler (Callback Callback, boolean Async) {<span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(find_potential_leaks) {<span class="hljs-keyword"><span class="hljs-keyword">Final</span></span> <span class="hljs-class"><span class="hljs-class"> <span class="hljs-keyword">Class</span><? <span class="hljs-keyword">extends</span> <span class="hljs-title">Handler</span>> <span class="hljs-title">Klass</span> = <span class="hljs-title">getclass</span>(); <span class="hljs-title">if</span> (<span class="hljs-title">Klass</span>. <span class="hljs-title">Isanonymousclass</span> () || <span class="hljs-title">Klass</span>. <span class="hljs-title">Ismemberclass</span> () || <span class="hljs-title">Klass</span>. <span class="hljs-title">Islocalclass</span> ()) && (<span class="hljs-title">Klass</span>. <span class="hljs-title"> GetModifiers</span>() & <span class="hljs-title">Modifier</span>. <span class="hljs-title">STATIC</span>) = = 0) {</span></span>LOG.W (TAG,<span class="hljs-string"><span class="hljs-string">"the following Handler class should be static or leaks might occur:"</span></span>+ Klass.getcanonicalname ()); }} Mlooper = Looper.mylooper ();<span class="hljs-keyword"><span class="hljs-keyword">if</span></span>(mlooper = =<span class="hljs-keyword"><span class="hljs-keyword">NULL</span></span>) {<span class="hljs-keyword"><span class="hljs-keyword">Throw</span></span> <span class="hljs-keyword"><span class="hljs-keyword">New</span></span>RuntimeException (<span class="hljs-string"><span class="hljs-string">"Can ' t create handler inside thread that have not called Looper.prepare ()"</span></span>); } Mqueue = mlooper.mqueue; Mcallback = callback; Masynchronous = async; }</span></span></span></code></pre><p><p>When the handler is created, the Looper object of the current thread is obtained through Mlooper = Looper.mylooper (), and the Looper object is the precondition for acquiring the MessageQueue Object. Handler is eventually called to this method when the message is sent by calling Handler.sendmessage (message):</p></p>Handler SendMessage method (the method that will eventually be called)<pre class="prettyprint"><pre class="prettyprint"><code class="hljs java"> <span class="hljs-keyword">public </span> <span class=" Hljs-keyword ">boolean </span> <span class=" hljs-title ">sendmessageattime </span> (Message msg, <span class="hljs-keyword">long </span> uptimemillis) {MessageQueue queue = mqueue; <span class="hljs-keyword">if </span> (queue = = <span class="hljs-keyword">null </span>) {runtimeexception e = <span class="hljs-keyword">new </span> runtimeexception (<span class=" Hljs-keyword ">this </span> + <span class=" hljs-string ">" sendmessageattime () called with no mqueue "</span>); LOG.W (<span class="hljs-string"> "Looper" </span>, e.getmessage (), e); <span class="hljs-keyword">return </span> <span class="hljs-keyword">false </span>; } <span class="hljs-keyword">return </span> enqueuemessage (queue, msg, uptimemillis); }</code></pre></pre><p><p>As you can see here, handler gets the MessageQueue object for the current Thread. Then call Enqueuemessage (queue, msg, uptimemillis); This method is the method in handler, not the Enqueuemessage method in messgaequeue, We look at the Enqueuemessage method in Handler:</p></p>The Enqueuemessage in handler<pre class="prettyprint"><pre class="prettyprint"><code class=" hljs java"> <span class="hljs-keyword">private</span><span class="hljs-keyword">boolean</span><span class="hljs-title">enqueueMessage</span><span class="hljs-keyword">long</span> uptimeMillis) { <span class="hljs-keyword">this</span>; <span class="hljs-keyword">if</span> (mAsynchronous) { msg.setAsynchronous(<span class="hljs-keyword">true</span>); } <span class="hljs-keyword">return</span> queue.enqueueMessage(msg, uptimeMillis); }</code></pre></pre><p><p>You can see the first line of code in a method body: Msg.target = this; Sets the currently sent Message.target object to the current Handler. This is called Msg.target.dispatchMessage (msg) in the Looper.loop () method. This will be introduced Soon. Let's not say This. As you can see, the Enqueuemessage method in handler sets the target of the message to the current object, and then calls the enqueuemessage of the MessageQueue object, which is described in Messagequeue. Is the method that is used to add messages to the message Queue) method, which adds a message to the MessageQueue Object.<br>ok, Now let's take a look at Handler's dispatchmessage (msg) method. Let's take a look at the source code for this method, which is used in the Looper loop method, and when each message is fetched, the method Msg.target.dispatchMessage (msg) is invoked to process each message.</p></p>DispatchMessage<pre class="prettyprint"><pre class="prettyprint"><code class="hljs cs"> <span class="hljs-keyword">public </span> <span class="hljs-keyword"> void </span> <span class="hljs-title">dispatchmessage </span> (Message msg) {<span class="hljs-keyword">if </span> (ms g.callback! = <span class="hljs-keyword">null </span>) {handlecallback (msg); } <span class="hljs-keyword">else </span> {<span class="hljs-keyword">if </span> (mcallback! = <span class="hljs -keyword ">null </span>) {<span class=" hljs-keyword ">if </span> (mcallback.handlemessage (msg)) { <span class="hljs-keyword">return </span>; }} Handlemessage (msg); } }</code></pre></pre><p><p>The method first to determine whether the message itself has a callback function, some call the message callback function, if not, then determine whether to create this handler when the callback interface is passed, note that the name of this interface is callback, Handler can assign a value to this mcallback by a constructor, and if the Mcallback passes the value, it will be called, otherwise the Handlemessage method of handler itself is Called. This method is empty in handler and needs to be overridden in a class that inherits Handler. This means that the overridden method is actually the Least-privileged.<br>The following two kinds of common, but the previous one, that is, the message itself carries the interface of the general through the Message.obtain (Handler h, Runnable Callback) method to Set.<br>okay, Android's Async Thread. It doesn't have much to do here.</p></p> <p><p>The asynchronous threading principle of Android</p></p></span>
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