0

I have created one demo class to test how to create thread by extending thread class. As we need to invoke start() on class object to call run() , but if I invoke run() directly by invoking it on class object it also get run. As it gets run then why should we call start() on class object to invoke run()

public class Derived extends Thread{

    public void run()
    {
        System.out.println("Run.....");
    }

    public static void main(String arg[]){
        Derived derivedThread = new Derived();   
        derivedThread.start();

    }

}

Above is the valid way, but when I call run() directly like,

public class Derived extends Thread{

    public void run()
    {
        System.out.println("Run.....");
    }

    public static void main(String arg[]){
        Derived derivedThread = new Derived();

        //derivedThread.start();
        derivedThread.run();
    }

}

Above code also run successfully.

Then why we call thread by first way. Can somebody clear it? Will appreciate your help.

juco
  • 6,331
  • 3
  • 25
  • 42
Anjali Yeole
  • 11
  • 1
  • 3
  • Nothing surprising, since [`Thread`](https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html) implements `Runnable`. – PM 77-1 Apr 11 '15 at 05:01
  • To see the difference put a Thread.sleep(1000) in your run() method and a println(....) just after you start or run your object. Run should be running synchronously when you call run but asynchronously when you call start. – redge Apr 11 '15 at 07:31
  • possible duplicate of [Why we call Thread.start() method which in turns calls run method?](http://stackoverflow.com/questions/8052522/why-we-call-thread-start-method-which-in-turns-calls-run-method) – Neeraj Jain Apr 11 '15 at 11:30

1 Answers1

0

There will be no thread created when you call the run(). It will act as an method call and do what is in the run() method.

But in the other hand. the start() will create a thread. and what the thread do is in the run() method

Anjula Ranasinghe
  • 584
  • 1
  • 9
  • 24