Hey guys in this post, we will discuss different ways of implementing Threads in Java.
Table of Contents
Introduction
Threads allow a program to operate more efficiently by doing multiple things at the same time.
Threads can be used to perform complicated tasks in the background without interrupting the main program.
Different ways of creating Threads
There are 2 different ways to create Threads in Java.
- By extending Thread class
- By implementing Runnable interface
By extending Thread class
First, let’s look at the syntax of creating a Thread
public class Main extends Thread {
public void run () {
System.out.println("This code is running in a thread");
}
}
In order the create Thread
we need to extend a Main
class with the Thread
class. Once we extend the Thread
class, we can able to override the run()
method.
Let’s look at the complete implementation –
public class Main extends Thread {
public static void main(String[] args) {
Main thread = new Main();
thread.start();
System.out.println("This code is running outside of the thread");
}
public void run () {
System.out.println("This code is running in a thread");
}
}
Inside the main()
, we call the start()
method to start the Thread
Output:
This code is running in a thread
This code is running outside of the thread
By implementing Runnable interface
First, let’s look at the syntax of creating Thread
public class Main implements Runnable {
public void run () {
System.out.println("This code is running in a thread");
}
}
We need to implement the Main
class with a Runnable
interface. Once we implement the Runnable
interface, we can able to override the run()
method.
Let’s look at the complete implementation –
public class Main implements Runnable {
public static void main(String[] args) {
Main obj = new Main();
Thread thread = new Thread(obj);
thread.start();
System.out.println("This code is running outside of the thread");
}
public void run () {
System.out.println("This code is running in a thread");
}
}
Inside the main()
method, we will create the Thread
object using a new
keyword, then on the thread object, we will call the start()
method to start the Thread
.
Output:
This code is running in a thread
This code is running outside of the thread