Is lesson me hum seekhenge:
- Executor kya hota hai
- Executor vs Thread
- Single Thread Executor
- Multi Thread Executor (Thread Pool)
- Future (result return)
- Complete workflow
Executor ek framework hai jo:
thread creation aur management ko simplify karta hai
Package:
java.util.concurrent
Problem with Thread:
❌ manually thread manage karna padta hai
❌ performance issue
❌ scalability problem
Solution:
✔ Executor framework use karo
Executor executor = Executors.newSingleThreadExecutor();1. Single Thread Executor
2. Fixed Thread Pool
3. Cached Thread Pool
✔ ek hi thread use hota hai
✔ tasks sequentially execute hote hain
import java.util.concurrent.*;
class Test {
public static void main(String[] args){
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(() -> {
System.out.println("Task 1");
});
executor.execute(() -> {
System.out.println("Task 2");
});
executor.shutdown();
}
}ExecutorService executor = Executors.newFixedThreadPool(3);✔ 3 threads ek saath kaam karenge
for(int i = 1; i <= 5; i++){
int num = i;
executor.execute(() -> {
System.out.println("Task " + num +
" by " + Thread.currentThread().getName());
});
}ExecutorService executor = Executors.newCachedThreadPool();✔ dynamic threads create karta hai
| Feature | Runnable | Callable |
|---|---|---|
| Return | ❌ No | ✔ Yes |
| Exception | ❌ No | ✔ Yes |
Future ek object hai jo:
future result ko represent karta hai
import java.util.concurrent.*;
class Test {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<Integer> task = () -> {
return 10 + 20;
};
Future<Integer> result = executor.submit(task);
System.out.println(result.get()); // wait and get result
executor.shutdown();
}
}| Method | Use |
|---|---|
| get() | result lena |
| isDone() | task complete check |
| cancel() | cancel task |
| Method | Use |
|---|---|
| execute() | Runnable |
| submit() | Runnable + Callable |
1. create executor
2. submit task
3. execute task
4. shutdown
executor.shutdown(); // graceful shutdown
executor.shutdownNow(); // immediate stopOffice me manager (Executor)
workers (threads)
tasks assign karta hai
✔ better performance
✔ thread reuse (thread pool)
✔ scalable
✔ easy management
✔ ExecutorService use karna best practice hai
✔ always shutdown executor
✔ Future async result handle karta hai
- Executor framework kya hota hai?
- Runnable vs Callable difference?
- Future kya hota hai?
- Fixed thread pool kya hota hai?
- execute() vs submit()?
Is lesson me humne seekha:
✔ Executor framework concept
✔ Single thread executor
✔ Multi-thread (thread pool)
✔ Callable & Future
✔ Task management
Executor framework Java me modern aur efficient multithreading solution provide karta hai.