Why we call Thread.start() method which in turns calls run method?

半城伤御伤魂 提交于 2019-11-27 00:41:41

[...] why not we directly call run() method?

The run() method is just an ordinary method (overridden by you). As with any other ordinary method and calling it directly will cause the current thread to execute run().

All magic happens inside start(). The start() method will cause the JVM to spawn a new thread and make the newly spawned thread execute run().

If you directly call run() method its body is executed in context of current thread. When you invoke start() method a new thread is created and run() method is executed in this new thread.

user1923551

Even if programmatically we are not creating any thread, For every application, O.S will create a default thread to execute its code with CPU.

Calling run method directly will make that run method execute in that main thread given by O.S.

But the intention of creating a thread class is to make sure that run method executes in a different thread. Unless thread manager of O.S creates a thread, your run method will not get executed in a separate thread. To request O.S to create the separate thread you have to call start() method which will send a request to O.S to create a thread. Once O.S creates a thread, then O.S will automatically call run method of your thread class in that newly created thread context. And hence your purpose of creating a separate thread and executing your run method in a separate thread will be served.

If you call run method directly, then it is like O.S is not creating any thread for you, and default main thread will execute your run method. No point of creating a separate thread class for that!

Hope I am clear. Let me know if you need more explanation to answer your question.

Note: Though books say JVM creates threads, internally JVM will have to send a request to thread manager driver of O.S layer to create a new thread in its thread pool. That's why I use O.S term more here than JVM.

Why do we call the thread object's start() method which in turns calls run() method

No it doesn't. start() calls the operating system, which starts a new thread, which (to simplify greatly) calls the run() method. Meanwhile the start() method has already returned to its caller. They are not equivalent.

Runnable is just an interface. A class implementing Runnable is nothing special, it just has a run method.

Thread#start is a natively implemented method that creates a separate thread and calls Thread's run method, executing the code in the new thread.

Thread implements Runnable. The code for run looks like this:

@Override
public void run() {
    if (target != null) {
        target.run();
    }
}

If the Thread instance was created by passing a Runnable to the Thread's constructor, the Runnable's run method is called.

Otherwise, classes extending Thread have to override the run method in order for start to work.

Calling run on Thread does NOT create a new thread.

If a thread has been instantiated but not started its is said to be in new state.
Unless until a start() method is invoked on the instance of the thread, it will not said to be alive.
If you do not call a start() method on the newly created thread instance thread is not considered to be alive.
If the start() method is not invoked and the run() method is directly called on the Thread instance, the code inside the run() method will not run in a separate new thread but it will start running in the existing thread.

SEE THE PROBLEM IN EXAMPLE

class Multi extends Thread{  
 public void run(){  
  for(int i=1;i<5;i++){  
    try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}  
    System.out.println(i);  
  }  
 }  
 public static void main(String args[]){  
  Multi t1=new Multi();  
  Multi t2=new Multi();  

  t1.run();  
  t2.run();  
 }  
}  

Output:1
       2
       3
       4
       5
       1
       2
       3
       4
       5

As you can see in the above program that there is no context-switching because here t1 and t2 will be treated as normal object not thread object.

Ravindra babu

It's due to the design of multithreading in Java.

Calling start () will start a new Thread and calling run() method does not start a new Thread.

If you call start() method on Thread, Java Virtual Machine will call run() method and two threads will run concurrently now - Current Thread and Other Thread or Runnable implementation.

Have a look at source code of start() method in Thread class

 /**
     * Causes this thread to begin execution; the Java Virtual Machine
     * calls the <code>run</code> method of this thread.
     * <p>
     * The result is that two threads are running concurrently: the
     * current thread (which returns from the call to the
     * <code>start</code> method) and the other thread (which executes its
     * <code>run</code> method).
     * <p>
     * It is never legal to start a thread more than once.
     * In particular, a thread may not be restarted once it has completed
     * execution.
     *
     * @exception  IllegalThreadStateException  if the thread was already
     *               started.
     * @see        #run()
     * @see        #stop()
     */
    public synchronized void start() {
        /**
         * This method is not invoked for the main method thread or "system"
         * group threads created/set up by the VM. Any new functionality added
         * to this method in the future may have to also be added to the VM.
         *
         * A zero status value corresponds to state "NEW".
         */
        if (threadStatus != 0)
            throw new IllegalThreadStateException();
        group.add(this);
        start0();
        if (stopBeforeStart) {
            stop0(throwableFromStop);
        }
    }

    private native void start0();

In above code, you can't see invocation to run() method.

private native void start0() is responsible for calling run() method. JVM creates native thread corresponding to java thread and call run() method.

Refer to this question for source code of native methods:

Where to find source code for java.lang native methods?

I presume you are talking about starting a thread. If that's the case the reason you don't invoke the run method directly is that you then would be calling the method, and not starting the thread.

Rohit Yadav

When we use start method then a new thread is created and then code inside the run method will be executed for each new Thread.

Use of start method creates two stack for each thread ,Stack and native stack.

But Run method call just execute the code inside the run method sequentially as run method call does not create different stacks.

Example

import java.util.concurrent.TimeUnit;

public class thread implements Runnable{

    /**
     * @param args
     */
    public static void main(String[] args) {
        Thread gg=new Thread(new thread());
        Thread gg1=new Thread(new thread());
        gg.run();
        gg1.start();
        /*gg.start();
        gg1.start();*/

    }

    @Override
    public void run() {
        for(int i=0;i<5;i++)
        {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        System.out.println("Hello..." + i);
        }

    }

}

If we want, we can call run() method, but if we call run method it will run as just a normal Java method. Whereas it we call start() it, JVM creates a new thread and run method will be executed on that thread.

Lokesh Kumar

start() and run() methods are used for running a thread.The run() method is just an ordinary method, it is overridden by the user and it will be called on the current thread. The start() method runs the run() method indirectly and creates a new thread.

Divya Paliwal

The difference is that if we execute the run method by start() method, it creates a new thread where we can execute run method otherwise the run() method will be executed in the thread created by JVM in the public static void main() method. This is exactly the whole point of multithreading, to run a different action on new threads.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!