The difference between thread start and run in Java

  • 2020-04-01 03:06:19
  • OfStack

Recently I saw a topic, the code is 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");
}

What is the output?

I ran it many times, and it turned out to be pong ping. Finally, the key point was discovered: the thread object, t, called not the start() method, but the run() method. Later, when I debug in breakpoint mode, I find that by calling the run() method, the entire program has only one thread, but after calling the start() method, the program will have one more thread. At this time, there is a CPU contention with the main thread, which may produce a variety of results. However, as the output method below is executed very quickly, 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 for client programmers to write their own functional code in. There is no difference between a direct call and a normal class calling its own member methods.
Start () marks the start of a thread, and when the method is called, a separate thread is added to the program, followed by the execution of the run() method.

So I think it's better to write a separate Thread than to inherit the Thread, and if you're implementing the interface, it's not convenient to call the new Thread(new YourRunnableClass()) into the main Thread or into the new Thread(new YourRunnableClass()).


Related articles: