Android thread and runable differences, explaining (in doubt)

Source: Internet
Author: User

Found that I have a wrong understanding of thread and runable, read the source after the distinction between the two.

One: Runable is just an interface that does not open a thread and is still running in the UI thread.                     

 Public Interface Runnable {    /**     * Starts executing the active part of the class ' Code. This method was     * Called when a thread was started that had been created with a class which     * Implements {@ Code  Runnable}.      */     Public void run ();}

 As you can see, runable only the Run method in the source code, and runable can execute the code to modify the UI in the main thread, and "OK" must be executed after outputting 10 "runable"  . Therefore, Runable does not have a thread open and is still running in the UI thread .

protected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Runnable.run (); LOG.D ("Hello", "OK"); } Runnable Runnable=NewRunnable () {@Override Public voidrun () { for(inti = 0;i<10;i++) {Textview.settext ("Runable"); LOG.D ("Hello", "runable"); }            }
};

Second: Thread How to open threads, and runable what relationship?

SOURCE section:

 Public class Implements Runnable {

The most direct part is the implementation of the Runable interface. Here's a look at the constructor for thread.

 Public Thread () {    Create (nullnullnull, 0);}

This is one of the enough functions to call the Create () method, and the other constructors still call the method. Look below for the Create () method.

Private voidCreate (Threadgroup Group,Runnable Runnable, String ThreadName,LongstackSize) {Thread CurrentThread=Thread.CurrentThread (); if(Group = =NULL) {Group=Currentthread.getthreadgroup (); }        if(group.isdestroyed ()) {Throw NewIllegalthreadstateexception ("Group already destroyed"); }         This. Group =Group; synchronized(Thread.class) {ID= ++Thread.count; }        if(ThreadName = =NULL) {             This. Name = "Thread-" +ID; } Else {             This. Name =ThreadName; }            this.target = runnable;
This. stackSize =stackSize; This. Priority =currentthread.getpriority (); This. Contextclassloader =Currentthread.contextclassloader; //Transfer over Inheritablethreadlocals. if(Currentthread.inheritablevalues! =NULL) {inheritablevalues=Newthreadlocal.values (currentthread.inheritablevalues); } //add ourselves to our threadgroup of choice This. Group.addthread ( This); }

Although more, but only to see this line of code, This.taeget = Runable, and in the thread class of the run () method and the Start () method,

   Public void run () {        ifnull) {            target.run ();        }    }

  

/*** Starts the new Thread of execution.     The <code>run () </code> method of * The receiver is called by the receiver Thread itself (and the     * Thread calling <code>start () </code>). *     * @throwsIllegalthreadstateexception-if This thread has already started. * @seeThread#run*/     Public synchronized voidstart () {checknotstarted (); Hasbeenstarted=true; Nativecreate ( This, stackSize, daemon);     }

These two form the difference of two methods:

    • Start

start the thread with the Start method, and actually implement multi-threaded operation , without waiting for the Run method body code to complete and proceed directly to execute the following code. By invoking the start () method of the thread class to start a thread, the thread is in a ready (operational) state and is not running, and once the CPU time slice is taken, the run () method is started, where the method run () is called the thread body, which contains the contents of the thread to be executed. This thread terminates when the Run method finishes running.

    • Run
       The run () method is just a common method of the class, if you call the Run method directly, the program is still only the main thread of the threads, its program execution path is only one, or to execute sequentially, or to wait for the Run method body execution before you can continue to execute the following code, This will not achieve the purpose of writing threads. Summary: Call the Start method to start the thread, and the Run method is just a normal method call to thread, or execute in the main thread. Both methods should be familiar, put code that needs to be processed in parallel in the run () method, and the start () method will automatically call the run () method, which is prescribed by the JVM's memory mechanism. and the run () method must be public access, and the return value type is void:

This is clearly visible, so how to turn on threads,

One of them, and the analogy above.

 thread t = new   Thread (runnable);        T.start ();    LOG.D ( "Hello", "OK"  = new   Runnable () { @Override  public  void                  run () {
Textview.settext (" runable "); for (int i = 0;i<10;i++ log.d ("Hello", "runable" ); } } };
    1. Executes the thread's construction method, and then executes the OnCreate method. This.target = runable;
    2. Execute the T.start () and wait for the CPU time slice to execute the run () method.
    3. Execute the Run () method, Target.run (); (That is, execute Runable.run () on the child thread.) )

Depending on the execution results, you see that the thread is actually turned on, and the output of "OK" is not in the order of code execution.

06-13 19:32:26.252 21369-21369/? D/HELLO:OK06-13 19:32:26.252 21369-21429/? D/HELLO:RUNABLE06-13 19:32:26.252 21369-21429/? D/HELLO:RUNABLE06-13 19:32:26.252 21369-21429/? D/HELLO:RUNABLE06-13 19:32:26.252 21369-21429/? D/HELLO:RUNABLE06-13 19:32:26.252 21369-21429/? D/HELLO:RUNABLE06-13 19:32:26.252 21369-21429/? D/HELLO:RUNABLE06-13 19:32:26.252 21369-21429/? D/HELLO:RUNABLE06-13 19:32:26.252 21369-21429/? D/HELLO:RUNABLE06-13 19:32:26.252 21369-21429/? D/HELLO:RUNABLE06-13 19:32:26.252 21369-21429/? D/hello:runable

but can you modify the UI (Textview.settext)?!!!!!! The execution is Runable.run (). (Should you not execute this sentence on a child thread?) Isn't a child thread unable to modify the UI? )

To add a button listener for it, print the name of the thread T, for Thread-76777 

  Button.setonclicklistener (new  View.onclicklistener () {            @Override            public  void  OnClick (View v) {                t.start ();            }        });

Get the results I want:: FATAL exception:thread-76777, Android.view.viewrootimpl$calledfromwrongthreadexception:

so the problem is. Why the above situation can be modified, and add button click after execution T.start () cannot modify UI.

I hope someone will see to help me answer this question, if this article has errors also want to point out.

Reason:

OnCreate in a very short period of time, the Viewrootimpl has not been created yet, and new Thread () is able to modify the UI.

Because at that time Viewrootimpl had not yet been created.

when the button is used, it will not work. Because this time the view tree must have been created. only the thread that created the view can modify and update the change view.
because Viewrootimpl is created in the main thread of the Activitythread class. So only the main thread can update the UI.

end!

Android thread and runable differences, explaining (in doubt)

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.