Interview question
What is Multithreading in Java? Explain the concept and advantages. Java में Multithreading क्या है? Concept और advantages explain करें।
Answer
Multithreading is executing multiple threads simultaneously within a single process. A thread is a lightweight sub-process that shares memory with other threads but has its own execution path and stack.
| Concept | Definition | Benefit |
|---|---|---|
| Thread | Lightweight execution unit | Parallel execution |
| Process | Heavy program instance | Isolation |
| Context Switching | Switch between threads | Concurrent execution |
| Time Slicing | OS allocates CPU time | Fair scheduling |
// Multithreading Example
public class MultiThreadingDemo {
public static void main(String[] args) {
// Create threads
Thread t1 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
System.out.println('Thread 1: ' + i);
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
System.out.println('Thread 2: ' + i);
}
});
// Start threads (not run)
t1.start();
t2.start();
// Both threads execute simultaneously
}
}
// Advantages of Multithreading:
// 1. Responsiveness - UI stays responsive
// 2. Resource sharing - threads share memory
// 3. Economy - thread creation is cheaper than processes
// 4. Scalability - better CPU utilization
// 5. Concurrent execution - tasks run in parallel
// 6. Better performance - on multi-core systemsMultithreading से multiple threads एक साथ execute हो सकते हैं।
Was this answer clear?