In an interview, many children will be asked questions about multithreading, using the creation method as a guide, and then throwing out how to start a thread, which will lead to the difference between start() and run(). I don’t remember how I answered it, but I’m sure it wasn’t very good…

The correct start mode — start()

As shown in the following code execution result, the output result is main, thread-0 (the default child Thread name is Thread+ increment).

The run() method prints directly to the current thread, not the child thread. After the start() method executes, the result is the child thread output.

    public static void main(String[] args) {
        Runnable runnable = () ->{
            System.out.println(Thread.currentThread().getName());
        };
        runnable.run();
        new Thread(runnable).start();
    }
Copy the code

From this we know that the start() side starts the thread correctly, because the intention is to create a new thread and start it. Just because the run method is just a normal Java method, it does not start the thread. Why do you say that? Let’s see how the official website explains:

If you call Thread’s run() without overwriting it, you do nothing and return. Even though the run method in Thread implements the Runable interface, it does not start the Thread itself. This is not substantially different from the run method in the Runable interface.

Call the start() method multiple times

The first call to start() will put the thread in a Runnable state, and a second call will throw an exception. Here is part of the source code for Thread:

// Determines the state of the thread
private volatile int threadStatus = 0; .// The first line in the start() line is to determine whether the current thread state is not 0 (no start value)
  public synchronized void start(a) {
        if(threadStatus ! =0)
            throw newIllegalThreadStateException(); . }Copy the code

Thus, when the start() method is executed with a volatile(synchronous) int modifier, when the thread has already called the start() method, the value of threadStatue will no longer be zero, so a call to start() will raise a judgment and throw an exception.

Since the start() method calls the run() method, why do we choose to call start() rather than run() directly?

As mentioned above, a single call to run(), like a pure Java method call, is called by the current thread, not the created child thread, which is against our purpose. The proper way to start a thread is the start() method, and a call to start() will enable the thread to run its normal life cycle.

conclusion

This article makes a simple comparison between the run() method and the start() method, which is meant to show the proper way to start a thread.