Android Handlerthread Source Code Analysis

Source: Internet
Author: User

Handlerthread Brief Introduction:

We know that the thread thread is a disposable consumer when the thread thread finishes running a time-consuming task. The thread will be destroyed on its own initiative. Suppose at this time I have another

Time-consuming task to run, we have to create the thread again to run the time-consuming task. However. There is a performance problem: Creating and destroying threads multiple times is a very costly

system resources. To understand this, we are able to build a cyclic thread looper thread on our own. When there are time-consuming tasks to run into the loop thread. Thread Run consumption

When the task runs, the loop thread waits until the next new time-consuming task is put in. This avoids the creation of a thread thread that causes multiple

Performance issues. Maybe you can build a looping thread on your own, but I can tell you a good news. The Aandroid SDK actually already has a looping threading framework

The At this point you just need to know how to use it OK! Of course we are the protagonist Handlerthread today!

Next, please handlerthread, clap ~ ~

The parent class of Handlerthread is thread, so handlerthread is actually a thread, just the inside helps you implement a looper loop.

Then we

Let's start by knowing how handler is used.

"Reprint Please specify Source: Android handlerthread Sources Analysis CSDN ruins of the tree"

Handlerthread Use steps: 1. Create an Instance Object
new HandlerThread("handlerThread");

The above parameters can be arbitrary strings. The role of the parameter is primarily to mark the name of the current thread.

2. Start the Handlerthread thread
handlerThread.start();

Here we build a looping thread.

Then you may wonder. So how do I put a time-consuming asynchronous task into a handlerthread thread to run it? Of course there is a way, next look at the third part.

3. Building a circular message processing mechanism
newnew Handler.Callback() {            @Override            publicbooleanhandleMessage(Message msg) {                //实现自己的消息处理                returntrue;            }        });

The third step creates a handler object. The Looper object in the above handlerthread is the most handler of the number of references. Then rewrite the handler in the callback interface class.

Handlermessage method to handle time-consuming tasks.

Summary: the above three-step sequence can not be chaotic, must strictly follow the steps. In this way, we are able to call Subhandler to send a message in the form of a time-consuming task to the thread

Run in Handlerthread. The implication is that the Handlermessage method in the callback interface class in Subhandler is actually running in a worker thread.

Handlerthread instances:
 PackageCom.example.handlerthread;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.HandlerThread;ImportAndroid.os.Message;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportAndroid.widget.TextView; Public  class mainactivity extends Activity {    PrivateHandler Msubhandler;PrivateTextView TextView;PrivateButton button;PrivateHandler.callback Msubcallback =NewHandler.callback () {//The implementation of this interface is to handle asynchronous time-consuming tasks, so the method runs in a child thread        @Override         Public Boolean Handlemessage(Message msg) {Switch(msg.what) { Case 0: Message MSG1 =NewMessage (); Msg1.what =0;                Msg1.obj = Java.lang.System.currentTimeMillis (); Muihandler.sendmessage (MSG1); Break;default: Break; }return false; }    };@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);        TextView = (TextView) Findviewbyid (R.id.textview);        Button = (button) Findviewbyid (R.id.button); Handlerthread Workhandle =NewHandlerthread ("Workhandlethread");        Workhandle.start (); Msubhandler =NewHandler (Workhandle.getlooper (), msubcallback); Button.setonclicklistener (NewOnclicklistener () {@Override             Public void OnClick(View v) {//delivery of asynchronous time-consuming tasks to HandlerthreadMsubhandler.sendemptymessage (0);    }        }); }}
Handlerthread Source Code Analysis Handlerthread construction method
/** * Handy class for starting a new thread the has a looper. The looper can then is * used to create handler classes. Note that start () must still is called. */ Public  class handlerthread extends Thread {    //Thread Priority    intmpriority;//When the front-thread ID    intMtid =-1;//When the Looper object is held by the front threadLooper Mlooper;//Construction method     Public Handlerthread(String name) {//Call the parent class default method to create the thread        Super(name);    mpriority = Process.thread_priority_default; }//Construction method with priority-Number of parameters     Public Handlerthread(String name,intPriority) {Super(name);    Mpriority = priority; }...............}

Analysis: This class begins with a descriptive narrative: This class is used to create a thread with a looper loop, Looper objects are used to create handler objects, and it is worth noting that the handler is created

object to start the thread before calling the start () method.

There may be some people here who have questions? Why do you need to call the start () method to create handler? We'll answer that later.

The above code gaze is already very clear. The Handlerthread class has two methods of construction. The difference is to set the priority parameters for the current thread. You can set priorities based on your own situation.

can also use the default priority.

Handlerthrad's Run method
 Public  class handlerthread extends Thread {  /** * Call back method that can is explicitly overridden if needed to execute some * setup before Looper loops     . */    protected void onlooperprepared() {    }@Override     Public void Run() {//Get the ID of the current threadMtid = Process.mytid ();//preparation cycle conditionsLooper.prepare ();//Hold lock mechanism to get the Looper object of the current thread        synchronized( This) {Mlooper = Looper.mylooper ();//Notifies that the current thread has created the Mlooper object successfully. This is mainly to notify the Getlooper method of waitNotifyall (); }//Set the priority of the current threadProcess.setthreadpriority (mpriority);//The method implementation body is empty, the subclass can implement the method, the function is to do some preparatory work before the thread loop. Of course, subclasses can also not be implemented. Onlooperprepared ();//Start loopLooper.loop (); Mtid =-1; }}

Analysis: The gaze in the above code has been written very clearly, the main function of the above run method is to call the Looper.prepare and Looper.loop build a loop thread.

Worth mentioning.

Is. The Onlooperprepared method is called before the loop loop is started in the Run method, and the implementation of the method is empty. The user is able to implement the method in the child class. The function of this method is

Do some initialization work before the thread loop, and of course you can not implement the method to see the requirements in detail.

As a result, Googleproject also takes into account the extensibility of the code when writing code. Cow b!

Handlerthread Other methods Getlooper get the Looper object of the current thread
 /** * This method returns the Looper associated with this thread. If This thread isn't been started * or for any reason are isAlive () returns False, this method would return null.       If this thread * have been started, this method would block until the Looper has been initialized.     * @return the Looper. */     PublicLooperGetlooper() {//Assume the thread is not alive. The null is returned directly        if(!isalive ()) {return NULL; }//If The thread has been started, wait until the Looper have been created.        //Assuming the thread has started, but Looper has not yet been created, wait and know that Looper was created successfully        synchronized( This) { while(IsAlive () && Mlooper = =NULL) {Try{Wait (); }Catch(Interruptedexception e) {                }            }        }returnMlooper; }

Analysis: In fact the English gaze at the beginning of the method has been explained very clearly: the main function of this method is to obtain the Mlooper object in the current Handlerthread thread.

The first inference is whether the current thread is alive, assuming it is not alive, which directly returns NULL.

Next, assume that the current thread is alive. The member variable mlooper of the inferred thread is null. assumed to be

NULL, which indicates that the current thread has been created successfully, but has not yet been able to create the Looper object, so the wait method is called here. After the Notifyall method call in the Run method

Notifies the current thread that the wait method waits for the end and jumps out of the loop. Gets the value of the Mlooper object.

Summary: There is a synchronization problem when acquiring the Mlooper object. Only when the thread is created successfully and the Looper object is created successfully can the Mlooper value be obtained. Here wait for the method wait and the Notifyall method in the Run method together to complete the synchronization problem.

Quit to end the loop of the current thread
 /** * Quits the handler thread ' s looper. * <p> * Causes the handler thread ' s looper to terminate without processing any * More messages in the MESSAG     E queue.     * </p><p> * Any attempt to post messages to the queue after the Looper are asked to quit would fail.     * For example, the {@link handler#sendmessage (Message)} method would return false. * </p><p class= "NOTE" > * Using This method may is unsafe because some messages may not be delivered *  Before the looper terminates.     Consider using {@link #quitSafely} instead to ensure *, pending work is completed in an orderly manner. * </p> * * @return True If the looper looper have been asked to quit or False if the * thread ha     D not yet started running. * * @see #quitSafely * *     Public Boolean quit() {Looper Looper = Getlooper ();if(Looper! =NULL) {looper.quit ();return true; }return false; }//Safe exit cycle  Public Boolean quitsafely() {Looper Looper = Getlooper ();if(Looper! =NULL) {looper.quitsafely ();return true; }return false; }

Analysis: There are two ways to get the current thread out of the loop, one that is safe, and one that is unsafe.

What is the difference between the two? The efficiency of quitsafely method is lower than the rate of quit method. But it's safe. The details of which to choose depends on the details of the project.

Summarize:

The 1.HandlerThread is useful for building loop threads.

2. You must call the Start method after you create handler as a Handlerthread thread message runner. Since the looper parameters required to create the handler are obtained from the Handlerthread class, the assignment of the Looper object is created in the Handlerthread run method.

3. For a combination of handlerthread and service please refer to a blog: Android intentservice source Code Analysis

"Reprint Please specify Source: Android handlerthread Sources Analysis CSDN ruins of the tree"

Android Handlerthread Source Code Analysis

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.