Difference between start and run of Thread

Source: Internet
Author: User

I recently saw a question with the following code:

= "Ping" "pong"

Q: What Will be output?

I run it many times and the result is pong ping. Later, the key point was found. The thread object t called not the start () method, but the run () method. Later, I opened the breakpoint mode debug and found that the entire program has only one thread to call the run () method. After the start () method is called, the program will have one more thread. In this case, there is a cpu contention with the main thread. There may be a variety of results, but the following output method will be executed soon, so it is basically the output of "ping pong.

 

So the difference between run () and start () is:

Run () is a method defined in the Runnable interface to allow client programmers to write their own functional code in this method. There is no difference between calling a member method directly and calling a common class.

Start () indicates the start of a thread. After this method is called, an independent thread is added to the program, and then the run () method is executed.

 

Therefore, I think it is best to inherit the Thread to write a separate Thread. If it is to implement the interface, it is still necessary to call the new Thread (new YourRunnableClass () in the main Thread, it is inconvenient.

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.