Answer to Question #230268 in Java | JSP | JSF for eksow

Question #230268

There are two ways to create threads in java, one by extending the Thread class and another is by implementing Runnable interface. When to use which option to create thread, which one is better and why? Explain with example.


1
Expert's answer
2021-08-30T02:29:10-0400

It is appropriate to use Thread

class when:

  • When there is no need for extending another class.
  • When there is no need for code reusability.

Runnable interface is appropriate when:

  • There is need to reuse code.
  • There is need to extend another class
  • When there is need for preventing overhead of any method

The best option is to use Runnable interface.

Example of creating a thread by extending the Thread class

class Example extends Thread{  
public void run(){  
System.out.println("Running...");  
}  
public static void main(String args[]){  
Example thread1=new Example();  
thread1.start();  
 }  
}  

An example of how to create a thread by Runnable interface:

class Example implements Runnable{  
//The method run being implemented
public void run(){  
System.out.println("Running thread...");  
}  
  
public static void main(String args[]){  
Example m1=new Example();  
Thread thread1 =new Thread(m1);  
thread1.start();  
 }  
}  

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS