android--'s understanding of handlerthread and the matters needing attention

Source: Internet
Author: User

SOURCE Analysis
 Public  class handlerthread extends Thread {    intmpriority;//Specify Thread priority    intMtid =-1; Looper Mlooper; Public Handlerthread(String name) {Super(name);    mpriority = Process.thread_priority_default; } Public Handlerthread(String name,intPriority) {Super(name);    Mpriority = priority; }protected void onlooperprepared() {    }@Override     Public void Run() {Mtid = Process.mytid ();The //prepare () method creates a Looper object and places the object in a variable (sthreadlocal) within that thread scope, initializing a MessageQueue during the construction of the Looper object. As the Looper object member variable. Looper.prepare ();//Create Looper and MessageQueue for child threads        synchronized( This) {Mlooper = Looper.mylooper (); Notifyall ();//Notify Getlooper () method Looper created} process.setthreadpriority (mpriority);        Onlooperprepared (); Looper.loop ();//Open looper, continuous loop from the MessageQueue to take the message processing, when there is no message will be blocked when the arrival of the message will wake upMtid =-1; } PublicLooperGetlooper() {if(!isalive ()) {return NULL; }//If The thread has been started, wait until the Looper have been created.        synchronized( This) { while(IsAlive () && Mlooper = =NULL) {Try{Wait ();//wait for the run () method to complete Looper creation}Catch(Interruptedexception e) {                }            }        }returnMlooper; } Public Boolean quit() {Looper Looper = Getlooper ();if(Looper! =NULL) {looper.quit ();return true; }return false; } Public Boolean quitsafely() {Looper Looper = Getlooper ();if(Looper! =NULL) {looper.quitsafely ();return true; }return false; } Public int GetThreadId() {returnMtid; }}
Usage

1. Create a handlerthread that creates a thread that contains looper.

new HandlerThread("test"// 开启线程

2, obtain the Handlerthread looper.

Looper looper = handlerThread.getLooper();

3, create handler, through Looper initialization.

Handler handler = new Handler(looper);

Now that we send the message through handler, we execute it in the child thread.

Always remember to exit handlerthread when you're done with it.

handlerThread.quit();
different from normal thread

1. Difference
Handlerthread inherits from Thread, calling start () actually calls the underlying run method, creates a looper with Message Queuing, and exposes the interface (Getlooper ()), providing its own Looper object, The Looper.loop () method is a dead loop by default, and the thread runs complete or the program exits by manually closing the Looper, which is different from the normal thread.

2. Advantages
1, we often in development using new thread () {}.start () this way to open a child thread, which creates multiple anonymous threads, consumes system resources, and Handlerthread comes with looper so that he can reuse the current thread through Message Queuing, Save system resource overhead. This is its advantage and disadvantage, each task will be carried out in a queue, one after another, once the queue has a task to execute too long, it will cause the subsequent tasks will be deferred processing.

2, the Android system provides the handler class inside the Looper default binding is the UI thread message queue, for non-UI thread and want to use the message mechanism, can only customize a thread, the Threads Run () method, through the Looper.prepare (); Looper.loop (); To turn on Looper and Message Queuing, it's actually the Google siege Lion. The handlerthread,handlerthread binding is its own message queue, which does not interfere with or block the UI thread. The Intentservice built-in is handlerthread as an asynchronous thread.

Precautions

Once we have used handlerthread, we need to pay special attention to setting different thread priorities for handlerthread, and the CPU will schedule optimizations for all threads based on the different thread priorities set.

Applicable scenarios

Because Handlerthread has its own message queue, it does not interfere with or block the UI thread, and it is more appropriate to handle tasks that take a long time . All we need to do is send the task to Handlerthread, and then just wait until the end of the task execution to notify the return to the main thread.

android--'s understanding of handlerthread and the matters needing attention

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.