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 of the ruins of the tree"
Handlerthread Use steps: 1. Create an Instance Object
HandlerThread handlerThread = 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
Handler subHandler = new Handler(handlerThread.getLooper(), new Handler.Callback() { @Override public boolean handleMessage(Message msg) { //实现自己的消息处理 return true; } });
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:
Package Com.example.handlerthread;import Android.app.activity;import Android.os.bundle;import Android.os.Handler; Import Android.os.handlerthread;import Android.os.message;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.textview;public Class Mainactivity extends Activity {private Handler msubhandler; Private TextView TextView; Private button button; Private Handler.callback Msubcallback = new Handler.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:messag E MSG1 = new Message (); 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 = new Handlerthread ("Workhandlethread"); Workhandle.start (); Msubhandler = new Handler (Workhandle.getlooper (), msubcallback); Button.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) { Delivery of asynchronous time-consuming tasks to Handlerthread in Msubhandler.sendemptymessage (0); } }); }}
Handlerthread Source Code Analysis Handlerthread construction method
/** * Handy class for starting a new thread that has a looper. The looper can then be * used to create handler classes. Note that start() must still be called. */public class HandlerThread extends Thread { //线程优先级 int mPriority; //当前线程id int mTid = -1; //当前线程持有的Looper对象 Looper mLooper; //构造方法 public HandlerThread(String name) { //调用父类默认的方法创建线程 super(name); mPriority = Process.THREAD_PRIORITY_DEFAULT; } //带优先级参数的构造方法 public HandlerThread(String name, int priority) { 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 be explicitly overridden if needed to execute some * setup before Looper loops. */ protected void onLooperPrepared() { } @Override public void run() { //获得当前线程的id mTid = Process.myTid(); //准备循环条件 Looper.prepare(); //持有锁机制来获得当前线程的Looper对象 synchronized (this) { mLooper = Looper.myLooper(); //发出通知,当前线程已经创建mLooper对象成功,这里主要是通知getLooper方法中的wait notifyAll(); } //设置当前线程的优先级 Process.setThreadPriority(mPriority); //该方法实现体是空的,子类可以实现该方法,作用就是在线程循环之前做一些准备工作,当然子类也可以不实现。 onLooperPrepared(); //启动loop Looper.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 not been started * or for any reason is isAlive() returns false, this method will return null. If this thread * has been started, this method will block until the looper has been initialized. * @return The looper. */ public Looper getLooper() { //如果线程不是存活的,则直接返回null if (!isAlive()) { return null; } // If the thread has been started, wait until the looper has been created. //如果线程已经启动,但是Looper还未创建的话,就等待,知道Looper创建成功 synchronized (this) { while (isAlive() && mLooper == null) { try { wait(); } catch (InterruptedException e) { } } } return mLooper; }
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 had not yet Started running. * * @see #quitSafely */public Boolean quit () {Looper Looper = Getlooper (); if (looper! = null) {looper.quit (); return true; } RETUrn false; }//Safe Exit Loop 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 of the ruins of the tree"
Scan code attention to the public number "Android knowledge spread", not regularly spread the basic knowledge of commonly used Android.
Android Handlerthread Source Analysis