The difference between thread start and run in Java _java

Source: Internet
Author: User

Recently saw a topic, the code is as follows:

Copy Code code as follows:

public static void Main (String args[]) {
Thread t = new Thread () {
public void Run () {
Pong ();
}
};
T.run ();
System.out.println ("ping");
}
static void Pong () {
System.out.println ("Pong");
}

Q, what will the results output?

I ran it many times and the result was Pong ping. Finally, the key point is found, thread object T, the call is not the start () method, but the run () method. I later opened the breakpoint mode debug, and found that the call to the run () method, the entire program has only one thread, and call the Start () method, the program will be more than one thread. At this point and the main thread contention CPU, there may be a variety of results, but because the following output method is quickly implemented, so basically is "ping pong" output.

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 a direct call and a normal class calling your own member methods.
The start () is the flag that the thread starts to run, and when this method is invoked, a separate thread is added to the program, and then the run () method is executed.

So I think, I want to write a separate thread, it is best to inherit thread to do, if it is to implement the interface, to the main thread, or to new thread (new Yourrunnableclass ()) to call, it is very inconvenient.

Related Article

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.