Handler and Runnable in Android

Source: Internet
Author: User
Tags message queue

Recently in a project, consider using handler to handle the network request, and then study the handler and runnable

First, look at the runnable in Java.

The Runnable interface should is implemented by any class whose instances is intended to being executed by a thread. The class must define a method of no arguments called run .

This interface was designed to provide a common protocol for objects, wish to execute code while they was active. For example, was Runnable implemented by class Thread . Being active simply means a thread has been started and have not yet been stopped.

In addition, Runnable provides the means for a class to is active while not subclassing Thread . A class that implements Runnable can run without subclassing by Thread instantiating a Thread instance and passing itself in as The target. In most cases, the Runnable interface should is used if you is only planning to override the run() method and no Thread other Methods. This was important because classes should not being subclassed unless the programmer intends on modifying or enhancing the fun Damental behavior of the class.

The description in this official document, it is good to see the original document, it is not translated.

In Java, runnable can realize the multi-threading of resource sharing, the online multi-sell ticket example, but looks a little blurry, for such a code

New myrunnable; New Thread (runnable, "a"). Start (); New Thread (runnable, "B"). Start ();

How is sharing of resources shared between them?

Now let's take a look at the example

 Public classMain { Public Static voidMain (string[] args) {NewMain (). Test (); }    voidTest () {myrunnable runnable=Newmyrunnable (); NewThread (runnable, "a"). Start (); NewThread (runnable, "B"). Start (); }
Public classMyrunnableImplementsrunnable{@Override Public voidrun () { for(inti=0;i<5;i++) {System.out.println (Thread.CurrentThread (). GetName ()+i); } } }}

Execution results

A0
B0
B1
B2
B3
B4
A1
A2
A3
A4

You can see that these two threads have been executed 5 times without affecting each other.

And then add a global variable inside our runnable class.

 Public classMain { Public Static voidMain (string[] args) {NewMain (). Test (); }    voidTest () {myrunnable runnable=Newmyrunnable (); NewThread (runnable, "a"). Start (); NewThread (runnable, "B"). Start (); }     Public classMyrunnableImplementsrunnable{intNum=0; @Override Public voidrun () { for(inti=0;i<5;i++) {                ++num; System.out.println (Thread.CurrentThread (). GetName ()+ i+ "--------" +num); }        }    }}

Execution results

B0--------2
B1--------3
A0--------2
B2--------4
A1--------5
B3--------6
A2--------7
B4--------8
A3--------9
A4--------10

You can see that this global variable is shared between two threads.

What does that mean? When a Runnable object is passed to multiple threads to execute, the run () method of the Runnable object executes in multiple threads, and the global variables are shared among those threads.

Therefore, we can act as a thread lock through a global variable such as:

 Public classMain { Public Static voidMain (string[] args) {NewMain (). Test (); }    voidTest () {myrunnable runnable=Newmyrunnable (); NewThread (runnable, "a"). Start (); NewThread (runnable, "B"). Start (); }     Public classMyrunnableImplementsrunnable{intNum=0; FinalString string = ""; @Override Public voidrun () {synchronized(string) { for(inti=0;i<5;i++) {                    ++num; System.out.println (Thread.CurrentThread (). GetName ()+ i+ "--------" +num); }            }        }    }}

The results of this implementation

A0--------1
A1--------2
A2--------3
A3--------4
A4--------5
B0--------6
B1--------7
B2--------8
B3--------9
B4--------10

This will only execute after the run () method in one thread finishes executing the other

and change the location of the sync lock.

 Public classMain { Public Static voidMain (string[] args) {NewMain (). Test (); }    voidTest () {myrunnable runnable=Newmyrunnable (); NewThread (runnable, "a"). Start (); NewThread (runnable, "B"). Start (); }     Public classMyrunnableImplementsRunnable {intnum = 0; FinalString string = ""; @Override Public voidrun () { for(inti = 0; I < 5; i++) {                synchronized(string) {++num; System.out.println (Thread.CurrentThread (). GetName ()+ i + "--------" +num); }            }        }    }}

Execution results

A0--------1
B0--------2
B1--------3
B2--------4
B3--------5
B4--------6
A1--------7
A2--------8
A3--------9
A4--------10

As you can see, two threads alternately execute, but only one thread of the

++ + i + "--------" + num);

After execution, another thread is executed, so the value of the global variable is incremented sequentially.

Then look at the handler post (Runnale) method in Android

 Public classMainactivityextendsappcompatactivity {Handler Handler=NewHandler (); @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Myrunnable myrunnable=Newmyrunnable ();    Handler.post (myrunnable); }    classMyrunnableImplementsrunnable{@Override Public voidrun () { for(inti=0;i<5;++i) {System.out.println (Thread.CurrentThread (). GetName ()+"---"+i); }        }    }}

As you can see, this runnable is actually running on the main thread, because handler is created on the main thread, bound to the main thread. Some novices might think this is a new thread, putting the time-consuming action inside the UI. The API description is as follows:

Causes the Runnable R to is added to the message queue. The runnable'll be run on the thread to which this handler is attached.

So we post two, code revision to

New myrunnable (); Handler.post (myrunnable); Handler.post (myrunnable) ;

Then the corresponding result

You can see that it is running in sequence, which also reflects the idea of handler Message Queuing.

Change it again.

New myrunnable (); Handler.post (myrunnable); Handler.post (myrunnable); System.out.println ("post Finish");

You can see that it is not executed immediately after post.

So how do you post a Runnable object to a child thread to execute it? This binds the handler to a child thread

 Public classMainactivityextendsappcompatactivity {handlerthread thread=NewHandlerthread ("Subthread"); Handler Handler=NULL; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Thread.Start (); Handler=NewHandler (Thread.getlooper ()); Myrunnable myrunnable=Newmyrunnable ();        Handler.post (myrunnable); System.out.println ("Post Finish"); }    classMyrunnableImplementsrunnable{@Override Public voidrun () { for(inti=0;i<5;++i) {System.out.println (Thread.CurrentThread (). GetName ()+"---"+i); }        }    }}

Execution Result:

Handler and Runnable in Android

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.