Different ways of creating Thread
There are 2 ways to create a Thread in java
Extending Thread class
Implementing Runnable Interface
1. By Extending the Thread Class
class Multithread extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multithread t1=new Multithread();
t1.start();
}
}
2.By Implementing Runnable Interface
class Multithreading implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multithreading thread=new Multithreading();
Thread t1 =new Thread(thread); // Using the constructor Thread(Runnable)
t1.start();
}
}
We can implement the above 2 methods using Anonymous inner class and Lambda Expression
Implementation of run method using Anonymous inner class
public class Main
{
public static void main(String[] args) {
System.out.println("Hello World");
Thread obj=new Thread(){
public void run(){
System.out.println("I using Anonymous inner class");
}
};
obj.start();
}
}
the above implementation can be implemented using Runnable Interface also
public class Main
{
public static void main(String[] args) {
System.out.println("Hello World");
Runnable obj=new Runnable(){
public void run(){
System.out.println("I am in using Anonymous inner class....");
}
};
Thread thread =new Thread(obj);
thread.start();
}
}
Implementation of run method using Lambda Expression
public class Main
{
public static void main(String[] args) {
System.out.println("Hello World");
Runnable obj= ()->System.out.println("I am in Thread class using Anonymous inner class....");
Thread thread =new Thread(obj);
thread.start();
}
}
Which is the best method to create a Thread and Why
Creating a thread by implementing a Runnable Interface is preferred because java does not support multiple inheritance so by implementing interface we can achieve multiple interface