In Java, multithreading allows programs to execute multiple tasks simultaneously using threads.
A thread is a lightweight sub-process that runs independently within a program.
Java provides two main ways to create and start threads:
✅ Creating a Thread by Extending the Thread Class
🔹 Steps:
Create a class that extends the
Threadclass.Override the
run()method with the code to execute.Create an object of your class.
Call the
.start()method to begin execution.
🧪 Example:
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
}
public static void main(String[] args) {
MyThread t1 = new MyThread(); // Create a thread object
t1.start(); // Start the thread
}
}📌 Explanation:
run() contains the task that will run in the new thread.
.start() actually starts the thread and calls run() internally.
If you call run() directly, it will not create a new thread — it will run in the main thread.
✅ Creating a Thread by Implementing the Runnable Interface
🔹 Steps:
Create a class that implements the
Runnableinterface.Override the
run()method.Create an object of your class.
Pass it to a
Threadobject.Call
.start()on theThreadobject.
🧪 Example:
class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable thread is running...");
}
public static void main(String[] args) {
MyRunnable task = new MyRunnable(); // Create task
Thread t1 = new Thread(task); // Pass to Thread
t1.start(); // Start the thread
}
}📌 Explanation:
Runnableis a functional interface with a single method:run().This is the preferred method as it allows your class to extend another class if needed.
🆚 Thread vs Runnable – Comparison Table
Feature | extends Thread | implements Runnable |
|---|---|---|
Inheritance | Cannot extend any other class | Can extend another class |
Flexibility | Less flexible | More flexible |
Object Sharing | Thread class handles everything | Runnable separates task from thread |
Preferred for | Simpler, quick usage | Real-world, large applications |
🧠 Notes on .start() vs .run()
Method | Description |
|---|---|
.start() | Starts a new thread and runs the |
.run() | Just calls the method like a regular function (no new thread) |
If you use .start(), the output appears in a new thread:
Thread is running...If you use .run() directly, the code runs like a normal method in the main thread.