Profile
1.start () and run () introduction
2.start () and run () Source view
3.start () and run () test
Start () and run () introduction
1. Using start when we started the thread, why not run? Because start () will open a new thread to execute, and run is just a common idea, which is equivalent to the current thread invocation and does not start a new thread;
2.start () can only be called once, and run () may be called multiple times
Start () and run () Source view
1. First look at the source of start (), Start () startup thread is actually started by start0 ()
Public synchronized voidstart () {/*** This method isn't invoked for the main method thread or ' system ' * Group threads Created/set up by The VM. Any of the new functionality added * to this method in the future May has to also is added to the VM. * * A Zero status value corresponds to state "NEW". */ if(Threadstatus! = 0) Throw Newillegalthreadstateexception (); /*Notify the group that this thread was about to being started * so that it can be added to the group's list of THR EADS * and the group ' s unstarted count can be decremented. */Group.add ( This); Add to Thread groupBooleanstarted =false; Try{start0 (); Call local method Start0 () to start a new thread started=true; } finally { Try { if(!started) {group.threadstartfailed ( This); } } Catch(Throwable ignore) {/*Do nothing . If Start0 threw a throwable then it 'll be is passed the call stack*/ } } } Private native voidStart0 (); Local Method Start0 ()
2.run () Source code
Public void run () { ifnull) { target.run (); } }
Just called the Run method inside the runnable, and did not create a new thread
Start () and run () test
The theory also looked, the source code also looked, the thread practice is not such
public class Startrun { public static void main (string[] args) {T Hread test =new Thread (new Runnable () {@Override public
void
run () {System.out.println (Thread.curren TThread (). GetName ()); } }); Test.run (); }} The output is main, which is the main thread, and no new thread is created
Public class Startrun { publicstaticvoid main (string[] args) { Thread Test= New Thread (new Runnable () { @Override publicvoid run () { System.out.println (Thread.CurrentThread (). GetName ()); } ); Test.start (); }} The corresponding output is thread-0, creating a new thread
The difference between a multithreaded start () and a run ()