In Java, a Thread is a lightweight subprocess—a unit of execution within a program that runs independently. Threads allow concurrent execution, meaning your program can perform multiple tasks at the same time, improving efficiency and responsiveness.
🧠 Why Use Threads?
Imagine you’re building a web application:
- One thread handles user input.
- Another fetches data from a database.
- A third updates the UI.
Without threads, these tasks would run one after the other, slowing everything down.
🧵 How to Create a Thread in Java
There are two main ways to create a thread:
1. By Extending the Thread
Class
class MyThread extends Thread {
public void run() {
System.out.println(“Thread is running…”);
}
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start(); // starts the thread
}
}
2. By Implementing the Runnable
Interface
class MyRunnable implements Runnable {
public void run() {
System.out.println(“Thread is running…”);
}
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
t1.start();
}
}
🔄 Thread Lifecycle
A thread goes through several states:
- New – Created but not started.
- Runnable – Ready to run.
- Running – Currently executing.
- Blocked/Waiting – Paused, waiting for resources.
- Terminated – Finished execution.
🧪 Real-World Example
In a test automation project:
“I used threads to run multiple test cases in parallel. Each test case was executed in a separate thread, reducing total execution time and improving CI/CD pipeline efficiency.”