In this tutorial, we will learn ways to create a Thread in Java. A Thread is a lightweight process and Java has a feature called multithreading which means we can run multiple threads simultaneously. There are two ways to create the thread in Java first one is by extending Thread class and the second one is by implementing Runnable interface.
Page Contents
Creating a thread using Thread Class:
In Java, we can inherit Thread class in our class to create threads. Thread class contain constructors and methods which makes it so easy to create and maintain a thread. Check out these few steps to create a thread using Thread class.
- First of all, inherit Thread class in your class.
- Override the run() method in your class.
- Use the start() method to start your thread.
Check out the following example. To understand it more wisely.
Example Program:
//Inherting Thread class in Example class
public class Example extends Thread{
//Overiding run method
public void run(){
for(int i=0;i<5;i++){
System.out.println(i);
}
}
public static void main(String args[]){
Example obj=new Example();
obj.start(); //using start() method to start thread
}
}
Output:
0
1
2
3
4
Creating a thread using the Runnable interface:
We know Multiple Inheritance is not allowed in Java and we know to perform multi-threading we have to inherit Thread class in our class. But in some scenarios, if a class already inheriting another class we cannot inherit Thread class. So in this kind of situation, we can implement Runnable interface to create a thread in class.
Runnable interface contains only one method which is run() method.
Example Program:
//Implementing Runnable interface in Example class
public class Example implements Runnable{
//Overiding run method
public void run(){
for(int i=0;i<5;i++){
System.out.println(i);
}
}
public static void main(String args[]){
Example obj=new Example();
Thread thread=new Thread(obj);
thread.start();//using start() method to start thread
}
}
Output:
0
1
2
3
4
It is important to note we know Runnable interface contains an only a single method which is run(). But we need the start() method to start a thread. So to get this start method we create an object of Thread class(check 12th line in the above example code) and we pass the object of our class in the constructor of Thread class. After that, we called the start method using thread class object.
Here is another example program. In which you can see how we can directly define and override run() method in the constructor of the Thread class.
Example Program:
public class Example {
public static void main(String args[]){
Thread thread=new Thread(new Runnable(){
public void run(){
for(int i=0;i<5;i++){
System.out.println(i);
}
}
});
thread.start();//using start() method to start thread
}
}
Output:
0
1
2
3
4