Handlerthread Introduction:
We know that thread threads are disposable, and threads are automatically destroyed when thread threads perform a time-consuming task. If I have another one at this time
A time-consuming task needs to be executed, we have to recreate the thread to perform the time-consuming task. However, there is a performance problem: Creating and destroying threads multiple times is a costly
system resources. In order to understand this problem, we can build a cyclic thread looper thread on our own, and when there are time-consuming tasks running into the loop thread, the thread execution consumes
When the task is executed, 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 that the Aandroid SDK actually has a looping thread frame
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 ~ ~
Handlerthread's parent class is thread, so handlerthread is actually a thread, but its internals help you implement a Looper loop. Then we
Let's start by knowing how handler is used!
"Reprint Please specify Source: Android handlerthread Source Analysis CSDN Ruins of the tree"
Handlerthread Use steps: 1. Create an Instance Object
new HandlerThread("handlerThread");
The above parameter can be any string, the function of the parameter is to mark the name of the current thread.
2. Start the Handlerthread thread
handlerThread.start();
Here we build a looping thread. So you might wonder, how do I put a time-consuming asynchronous task into a handlerthread thread to execute 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 is to create a handler object that will handler the Looper object in the above Handlerthread, and then override the handler in the callback interface class.
Handlermessage method to handle time-consuming tasks.
Summary: the above three-step sequence can not be messy, must follow the steps strictly. In this way, we can call Subhandler to send the time-consuming task to the thread in the form of sending a message
Handlerthread to execute. The implication is that the Handlermessage method in the callback interface class in Subhandler is actually executed in the 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 executes 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 parameters Public Handlerthread(String name,intPriority) {Super(name); Mpriority = priority; }...............}
Analysis: This class begins with a description: The 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 before you can create handler? We'll answer that later.
The above code comment is already clear, the Handlerthread class has two constructor methods, the difference is to set the priority parameters of the current thread. You can set the priority according to your own situation
Level, or you can 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 ();//Notify that the current thread has created the Mlooper object successfully, which is primarily to notify the wait in the Getlooper methodNotifyall (); }//Set the priority of the current threadProcess.setthreadpriority (mpriority);//The method implementation body is empty, the subclass can implement the method, the role is to do some preparatory work before the thread loop, of course, the subclass can not be implemented. Onlooperprepared ();//Start loopLooper.loop (); Mtid =-1; }}
Analysis: The comments in the above code are clearly written, the main function of the above run method is to call the Looper.prepare and Looper.loop to build a looping thread. Worth mentioning.
Yes, the Onlooperprepared method is called before the loop loop is started in the Run method, and the implementation of the method is empty, and the user can implement the method in the subclass. The function of this method is
Do some initialization work before the thread loop, of course you can not implement the method, depending on the requirements. As you can see, Google engineers also take into account the extensibility of the code as they write 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() {//If the thread is not alive, it returns null directly if(!isalive ()) {return NULL; }//If The thread has been started, wait until the Looper have been created. //If 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 method at the beginning of the English note has been explained very clearly: the main function of this method is to obtain the current handlerthread thread of the Mlooper object.
It first determines whether the current thread is alive, and if it is not, returns null directly. Second, if the current thread survives, determine if the thread's member variable mlooper is null if the
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 to wait, after the Notifyall method call in the Run method
Notifies the current thread that the wait method waits for the end, jumps out of the loop, and obtains the value of the Mlooper object.
Summary: There is a synchronization problem when acquiring the Mlooper object, and the value of Mlooper can only be obtained if the thread is created successfully and the Looper object is created successfully. Here wait for the method wait and the Notifyall method in the Run method to complete the synchronization problem together.
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 that of the Quit method, but it is safe. The specific choice of which depends on the specific project.
Summarize:
The 1.HandlerThread is useful for building loop threads.
2. The Start method must be called when creating handler as the Handlerthread thread message performer, because the Looper parameters required to create the handler are obtained from the Handlerthread class, The assignment of the Looper object is also created in the Handlerthread run method.
3. For a combination of handlerthread and service, please refer to another blog: Android intentservice source Code Analysis
"Reprint Please specify Source: Android handlerthread Source Analysis CSDN Ruins of the tree"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Android Handlerthread Source Analysis