Is lesson me hum seekhenge:
- Runnable kya hota hai
- Runnable vs Thread class
- Runnable ka use kyun karte hain
- Implementation aur examples
- Best practices
Runnable ek interface hai:
jo thread ka task define karta hai
Package:
java.lang.Runnable
public void run();Ye method:
thread ka actual work define karta hai
Thread banane ke 2 tarike:
1. Thread class extend karke
2. Runnable implement karke
Runnable better hai kyunki:
✔ multiple inheritance possible hai
✔ clean design hota hai
class MyTask implements Runnable {
public void run(){
for(int i = 1; i <= 3; i++){
System.out.println("Running: " + i);
}
}
public static void main(String[] args){
MyTask task = new MyTask();
Thread t1 = new Thread(task);
t1.start();
}
}Runnable object → Thread object → start() → run()
class MyTask implements Runnable {
public void run(){
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args){
MyTask task = new MyTask();
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
}
}public class Test {
public static void main(String[] args){
Runnable task = () -> {
System.out.println("Thread running");
};
Thread t = new Thread(task);
t.start();
}
}| Feature | Runnable | Thread |
|---|---|---|
| Type | Interface | Class |
| Inheritance | possible | not possible |
| Flexibility | high | low |
❌ Direct run() call:
task.run(); // wrong✔ Correct:
t.start();Task define alag, execution alag
Jaise:
chef (task) + worker (thread)
✔ Runnable preferred approach hai
✔ run() method me logic likhte hain
✔ Thread object se execute hota hai
- Runnable kya hota hai?
- Runnable aur Thread me difference?
- run() aur start() me difference?
- Runnable better kyun hai?
Is lesson me humne seekha:
✔ Runnable interface
✔ Thread creation using Runnable
✔ Lambda usage
✔ Runnable vs Thread
Runnable Java me clean aur flexible multithreading approach provide karta hai.