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?
Submitted by Preeti Jain, on February 07, 2018

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.
  • 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.

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 

Read more...

  1. Explain life cycle of a thread in java.
  2. How to Create Java Threads (java examples to create threads)?
  3. Thread Synchronisation in Java with Example.
  4. Java program to demonstrate example of thread.
  5. Java program to Join Threads.





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.