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


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

This question will test your basic knowledge 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 don’t override run() method newly created thread won’t be called and nothing will happen.

class MyThread extends Thread {
   //don't override run() method
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class DontOverrideRun {
   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.
main has ended.
*/
As we saw in output, we didn’t override run() method that’s why on calling start() method nothing happened.


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

What will happen if we override start method of thread?






RELATED LINKS>
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?



No comments:

Post a Comment