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.
It is appropriate to use Thread
class when:
Runnable interface is appropriate when:
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();
}
}
Comments
Leave a comment