In this chapter of multithreading, we will learn How to create Thread in Java.
Multithreading is a concept of running more than one thread concurrently to perform any task. In Java, we can create threads using two ways:
- Extending the Thread class
- Implementing the Runnable Interface
1. How to Create Thread by extending the Thread class:
For creating a thread in Java extending the Thread class is a very common method and now we are going to design a class that extends java.lang.Thread class.
public class DemoClass extends Thread {
//overriding the run() method from Thread Class
public void run() {
System.out.println("Thread is running");
}
public static void main(String[] args) {
DemoClass object = new DemoClass();
// starting thread
object.start();
}
}
Output:
Thread is running
2. How to Create Thread by implementing Runnable Interface:
For creating a thread in Java by implementing the Runnable Interface we need to override the run() method and now we are going to design a class that implements the Runnable Interface.
public class DemoClass implements Runnable{
@Override
public void run() {
System.out.println("Thread is runnning");
}
public static void main(String[] args) {
DemoClass obj = new DemoClass();
Thread thread1 = new Thread(obj);
thread1.start();
}
}
Output:
Thread is running
3. Thread Class vs Runnable Interface
Here is an interesting question that what is the difference between creating a thread using Thread class and Runnable Interface?
Basically, there are two big reasons:
- In Java, Multiple Inheritance is not supported i.e if you create a thread using Thread class, you can not extend any other class. Therefore, in that case, creating a thread using Runnable Interface is recommended.
- But, while creating thread using Runnable Interface, you cannot achieve basic functionality like using methods that are available in Thread class like yield(), isAlive(), getState(), getId(), etc
I hope you understand how to Create Thread in Java. The creation of a thread through any of the method totally depends on your project requirement.
Official Docs: Visit Here