What will happen if we override start method of thread in java?


What will happen if we override start method of thread?

This question will again test your basic core java knowledge how overriding works at runtime, what what will be called at runtime and how start and run methods work internally in Thread Api.

When we call start() method on thread, it internally calls run() method with newly created thread. So, if we override start() method, run() method will not be called until we write code for calling run() method.


class MyThread extends Thread {
   @Override
   public void run() {
          System.out.println("in run() method");
   }
  
   @Override
   public void start(){
          System.out.println("In start() method");
   }
  
}

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class OverrideStartMethod {
   public static void main(String[] args) {
          System.out.println("main has started.");
         
          MyThread thread1=new MyThread();
          thread1.start();
         
          System.out.println("main has ended.");
   }
}
/*OUTPUT
main has started.
In start() method
main has ended.
*/
If we note output. we have overridden start method and didn’t called run() method from it, so, run() method wasn’t call.


Must read to get in depth  knowledge of run() and start() methods-

What will happen if we don’t override run method of thread?






RELATED LINKS>

Thread basics >

What is thread in java

Thread states/ Thread life cycle in java

Difference between Process and Thread in java

Implementing Threads in java by implementing Runnable interface and extending Thread class

When threads are not lightweight process in java, in fact they become heavy weight process


run() and Start() methods >

What will happen if we don’t override run method of thread?

What will happen if we override start method of thread?

Difference between starting thread with run() and start() methods in java


Can we start Thread again?

eEdit
Must read for you :