Home »
Java programming language
What will happen if we don't override thread class run() method in java?
In this article, we are going to learn what will happen if we don't override thread class run() method in java?
By Preeti Jain Last updated : January 26, 2024
run() method in Java
- In Thread class, run() method is defined with an empty implementation.
- If we override run() method in the user-defined thread then in run() method we will define a job and Our created thread is responsible to execute run() method.
- It is highly recommended to override run() method because it improves the performance of the system.
Answer
If we don't override Thread class run() method in our defined thread then Thread class run() method will be executed and we will not get any output because Thread class run() is with an empty implementation.
More Examples
Example 1
Here, we will see, what will happen if we override run() of Thread class?
class OverrideRunMethod extends Thread{
public void run(){
System.out.println("I am in run() method");
}
}
class MainMethodClass{
public static void main(String[] args){
OverrideRunMethod orn = new OverrideRunMethod();
orn.start();
}
}
Output
D:\Java Articles>java MainMethodClass
I am in run() method
Example 2
Here, we will see, what will happen if we don't override run() of Thread class?
abstract class NotOverridableRunMethod extends Thread{
abstract public void run();
}
class ParentMain{
public static void main(String[] args){
OverrideRunMethod orn = new OverrideRunMethod();
orn.start();
System.out.println("Thread class run() method will be executed with empty implementation");
}
}
When we call start() method of Thread class. It will perform some task like call run() method and allocate thread scheduler etc. First newly thread created run() will be executed if run() method does not exist then it will check its parent class(Thread class) exists if exists then its run() method will be executed .
Output
D:\Java Articles>java ParentMain
Thread class run() method will be executed with empty implementation
I am in run() method