Several ways Android starts a new thread

Source: Internet
Author: User

A:

public class HandlerTest01 extends Activity {    @Override public    void OnCreate (Bundle savedinstancestate) {        Super.oncreate (savedinstancestate);        Setcontentview (r.layout.main);                System.out.println ("activity->" + thread.currentthread (). GetId ());        Handler.post (R);    }     Private Handler Handler = new Handler ();    Private Runnable R = new Runnable () {        @Override public        void Run () {            try {                thread.sleep ()            } c Atch (interruptedexception e) {                //TODO auto-generated catch block                e.printstacktrace ();            }            System.out.println ("runnalbe->" + thread.currentthread (). GetId ());}}    ;}

The output from this example can be found to be the same as the ID of the Runnable object and the main user interface thread. In this example, we post a Runnable object directly using the handler object, which is equivalent to calling the run function of the Runnable object directly, and saying that run () is not called by the start function, then a new thread is not created. Instead, the run () method is called directly inside the original thread, so the output thread ID is the same.

B:

Handlerthread Handlerthread =NewHandlerthread ("MyThread"); Handlerthread.start ();PrivateMyHandler handler =NewMyHandler (Handlerthread.getlooper ());classMyHandlerextendsHandler { PublicMyHandler () {} PublicMyHandler (Looper Looper) {Super(Looper);  The following example shows how to open a new thread and process the message through handler. Handlertest02.java Public classHandlerTest02extendsActivity {PrivateMyHandler MyHandler =NULL; @Overrideprotected voidonCreate (Bundle savedinstancestate) {//TODO auto-generated Method Stub        Super. OnCreate (savedinstancestate);  This. Setcontentview (R.layout.main); System.out.println ("Activity->" +Thread.CurrentThread (). GetId ()); //generates a Handlerthread object that uses Looper to handle Message QueuingHandlerthread thread =NewHandlerthread ("MyThread"); //This thread must be startedThread.Start (); //binds a thread to a handler object, the handler object can handle the thread's message queueMyHandler =NewMyHandler (Thread.getlooper ()); //get the Message object from the handlerMessage msg =Myhandler.obtainmessage (); //Sends a MSG object to the target object handlerMsg.sendtotarget (); }     classMyHandlerextendsHandler { PublicMyHandler () {}//Constructors with parameters         PublicMyHandler (Looper Looper) {Super(Looper); } @Override Public voidhandlemessage (Message msg) {System.out.println ("Myhandler->" +Thread.CurrentThread (). GetId ()); }    }}

Based on the results returned by this example, it can be seen that the new thread ID differs from the thread ID of the main user interface. Because we called the Thread.Start () method, we really created a new thread that was in a different thread context than the original thread, so the print output had a different thread ID.

C:

public class ThreadTest extends Activity {    @Override    protected void onCreate (Bundle savedinstancestate) {        / /TODO auto-generated Method Stub        super.oncreate (Savedinstancestate);        This.setcontentview (r.layout.main);        System.out.println ("activity->" + thread.currentthread (). GetId ());                Thread thread = new Thread (r);        Thread.Start ();        try {            thread.currentthread (). Sleep (n),        } catch (Interruptedexception e) {            //TODO auto-generated Catch block            e.printstacktrace ();        }        Thread.stop ();    }     Runnable r = new Runnable () {        @Override public        void Run () {            System.out.println ("runnable->" + THREAD.C Urrentthread (). GetId ());}}    ;}

When the new thread creates an object, it passes in an object of the Runnable class, overloads the Run () method in the Runnable object, executes the time-consuming operation, and the new thread instance executes the Start method, opening a new thread to execute the Runnable's Run method.

D:

Handler MyHandler = new Handler () {public    void Handlemessage (Message msg) {        updateuihere ();    }} New Thread () { Public    void Run () {        dostuff ();         Execute time-consuming operation        Message msg = Myhandler.obtainmessage ();        Bundle B = new bundle ();        B.putstring ("Key", "value");        M.setdata (b);    Add data to the message        Myhandler.sendmessage (m);    Send message to handler, update UI    }}.start ();

  

Several ways Android starts a new thread

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.