Introduction to Multithreading in Java
Multithreading in Java is a feature that allows concurrent execution of two or more parts of a program to maximize CPU utilization. Each part is called a thread, and each thread defines a separate path of execution.
Java में Multithreading एक सुविधा है जो प्रोग्राम के कई हिस्सों को एक साथ (concurrently) चलाने की अनुमति देती है ताकि CPU का अधिकतम उपयोग किया जा सके। प्रत्येक हिस्सा एक थ्रेड (Thread) कहलाता है और यह एक अलग execution path होता है।
Advantages of Multithreading
- Improved performance through parallel execution
- Better CPU utilization
- Useful in real-time systems like gaming, animations, web servers
- Parallel execution से प्रदर्शन में सुधार
- CPU का बेहतर उपयोग
- Gaming, Animation, और Web Servers जैसे real-time systems में उपयोगी
Example: Basic Thread in Java
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread running: " + i);
}
}
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();
}
}
Expected Output
Thread running: 1
Thread running: 2
Thread running: 3
Thread running: 4
Thread running: 5
This output shows that the thread is executing independently using the run()
method triggered by start()
.
यह output दर्शाता है कि thread स्वतंत्र रूप से execute हो रहा है, जिसे start()
के माध्यम से run()
method चलाता है।