1, thread start-up

Source: Internet
Author: User

We are going to start a thread, which is to call the start method of a thread instance. Let's take a look at the source of the Start method:

1  Public synchronized voidstart () {2 3  //A value of 0 means that the thread is newly started.4   if(threadstatus!=0) {5     Throw Newillegalthreadstateexception ();6   }7   8   //The notification line Cheng, this thread has been started, and the line Cheng "No startup Quantity" attribute will be reduced by one. 9Group.add ( This);Ten    One   BooleanStarted=false; A   Try { -Start0 ();//calls the local method, which is assigned by the operating system to a thread -Started=true; the}finally { -     Try { -       if(!started) { -Group.threadstartfailed ( This); +       } -}Catch(Throwable ignore) { +       //don't do anything. If Start0 throws a run-time exception, it discards the call stack.  A     } at   } -}

If we call the Run method directly as follows:

1  Public classThreadTest {2     Public Static voidMain (String[]args) {3MyThread mythread=NewMyThread ();4 Mythread.run ();5Mythread.sleep (1000);6 System.out.println (Thread.CurrentThread (). GetName ());7    }8 }9 Ten  One classMyThreadextendsThread { A      Public voidrun () { -System.out.println ("MyThread:" +Thread.CurrentThread (). GetName ()); -     } the}

Program Run Result:

Mythread:main

Main

Conclusion:

Calling run does not produce a new thread, they are still in the same main thread.

This also means that the new thread is not generated by the programmer, but the programmer calls the Start method, and when the program runs to the end of the Start method, the Start method ends. The new thread is generated indirectly by the JVM and goes to call the Run method.

If we call the Run method directly the same as a normal method call.

1, thread start-up

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.