🔹 Introduction
Multithreading is a very important topic in Java interviews, especially for backend roles.
👉 One of the most commonly asked questions is:
How to create and run a thread using Runnable?
In this article, we will understand it step by step with examples.
🔹 Problem Statement
Create a thread in Java using the Runnable interface and execute it.
🔹 What is Runnable?
Runnable is a functional interface in Java that contains only one method:
public interface Runnable {
void run();
}
👉 It is used to define a task that can be executed by a thread.
🔹 Approach
-
Create a class that implements
Runnable -
Override the
run()method -
Pass object to
Thread -
Call
start()
🔹 Java Code (Runnable Implementation)
class MyTask implements Runnable {
public void run() {
System.out.println("Thread is running...");
}
}
public class Main {
public static void main(String[] args) {
MyTask task = new MyTask();
Thread thread = new Thread(task);
thread.start();
}
}
🔹 Output
Thread is running...
🔹 Using Lambda (Modern Approach)
Since Runnable is a functional interface, we can use lambda expressions.
👨💻 Java Code (Lambda)
public class Main {
public static void main(String[] args) {
Runnable task = () -> {
System.out.println("Thread running using lambda...");
};
Thread thread = new Thread(task);
thread.start();
}
}
🔍 Important Interview Point
👉 Difference between start() and run():
-
start()→ creates new thread -
run()→ runs in same thread
🔹 Time Complexity
- Depends on task (not fixed)
🔹 Key Takeaways
✔ Runnable is preferred over extending Thread
✔ Supports multiple inheritance
✔ Lambda makes code concise
✔ Very common interview question
🔹 Conclusion
Understanding threads and Runnable is essential for backend and concurrent programming.
Comments
Post a Comment