Runnable Interface in Java
The Runnable interface in Java is used to implement multithreading. It provides a way to create threads by defining the thread logic inside the run() method without extending the Thread class.
Java में Runnable interface का उपयोग multithreading के लिए किया जाता है। इसमें run() method के अंदर thread की logic को define किया जाता है, जिससे Thread class को extend करने की आवश्यकता नहीं होती।
Why Use Runnable Interface?
- Java supports only single inheritance. So if a class already extends another class, it cannot extend
Thread, but it can implementRunnable. - Keeps your code more modular and reusable.
- Java में केवल single inheritance होता है। यदि कोई class पहले से किसी और class को extend कर रही है, तो वह
Threadको extend नहीं कर सकती लेकिनRunnableको implement कर सकती है। - Code को modular और reusable बनाने में मदद करता है।
Example: Using Runnable Interface
class MyRunnable implements Runnable {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Runnable thread running: " + i);
}
}
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread t1 = new Thread(myRunnable);
t1.start();
}
}
Expected Output
Runnable thread running: 1
Runnable thread running: 2
Runnable thread running: 3
Runnable thread running: 4
Runnable thread running: 5
This output shows how the Runnable interface allows thread execution without extending the Thread class.
यह output दिखाता है कि कैसे Runnable interface का उपयोग करके Thread class को extend किए बिना ही multithreading की जाती है।