Introduction: Multithreading Kya Hoti Hai?
Multithreading ek process hota hai, jisme multiple threads ek hi program mein simultaneously kaam karte hain.
Thread Definition:
Thread ek lightweight sub-process hota hai jo independently chal sakta hai, lekin thread main program ka hi part hota hai.
Real Life Example:
Socho aap ek browser use kar rahe ho:
- Ek tab video chala raha hai
- Dusra tab file download kar raha hai
- Teesra tab web page open kar raha hai
Har kaam alag-alag thread mein chal raha hota hai ise hi Multithreading.
Benefits of Multithreading
- Fast execution (kyunki kaam parallel hota hai)
- Efficient CPU utilization
- Better user experience (lag kam hota hai)
- Useful in games, animations, servers, etc.
Thread Kaise Banate Hain?
Java mein ham threads do tareeko se banate hai.
- Thread class: Isme ham Thread class ka use karte hai.
- Runnable class: Ye ek interface hota hai. ye bhi java mein
Thread
banane ke liye use hota hai.
1. Using Thread
Class:
class MyThread extends Thread {
public void run() {
System.out.println("Thread Running...");
}
}
public class TestThread {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start(); // run() method ko call karega
}
}
2. Using Runnable
Interface:
class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable thread running...");
}
}
public class TestRunnable {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
t.start();
}
}
Thread Lifecycle (State Diagram):
Thread Lifecyle ka matlab hai ek Thread
creation se termination tak kis kis phases/stages se guzarta hai. Ek Thread
ki mainly 5 stages hoti hai.
- New – Thread object create hota hai.
- Runnable – start() method ke baad, ready to run.
- Running – CPU thread ko execute karta hai.
- Blocked/Waiting – thread kisi resource ka wait kar raha hai, jaise Input/Output, File Operation, and API call etc.
- Terminated/Dead – thread ka kaam khatam ho gaya.
Sleep, Join, Priority – Common Thread Methods
start()
Thread ko start karta hai.run()
Logic likhne ke liye (direct call mat karo)sleep(ms)
Thread ko kuch time ke liye sleep kara deta haijoin()
Wait karta hai jab tak dusra thread complete hosetPriority()
Thread ki importance set karta hai
1. start()
Example:
class MyThread extends Thread {
public void run() {
System.out.println("Thread running...");
}
}
public class StartExample {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start(); // run() ko internally call karega
System.out.println("Main thread ended");
}
}
Output:
Thread run ho raha hai...
Main thread khatam
2. run()
Example:
class MyThread extends Thread {
public void run() {
System.out.println("run() method chal raha hai");
}
}
public class RunExample {
public static void main(String[] args) {
MyThread t = new MyThread();
// t.run(); // isse thread nahi chalega, normal method call hoga
t.start(); // ye sahi tareeka hai
}
}
Output:
run() method chal raha hai
3. sleep(ms)
Example:
public class SleepExample {
public static void main(String[] args) throws InterruptedException {
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
Thread.sleep(1000); // Stop for 1 second
}
}
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
4. join()
Example:
class MyThread extends Thread {
public void run() {
for(int i = 1; i <= 5; i++) {
System.out.println("Child thread: " + i);
}
}
}
public class JoinExample {
public static void main(String[] args) throws InterruptedException {
MyThread t = new MyThread();
t.start();
t.join(); // main thread wait karega jab tak t thread complete na ho
System.out.println("Main thread ki last line");
}
}
Output:
Child thread: 1
Child thread: 2
Child thread: 3
Child thread: 4
Child thread: 5
Main thread ki last line
5. setPriority()
Example:
class MyThread extends Thread {
public void run() {
System.out.println(Thread.currentThread().getName() + " with Priority: " + getPriority());
}
}
public class PriorityExample {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
t1.setPriority(Thread.MIN_PRIORITY); // 1
t2.setPriority(Thread.MAX_PRIORITY); // 10
t3.setPriority(Thread.NORM_PRIORITY); // 5 (default)
t1.start();
t2.start();
t3.start();
}
}
Output:
Thread-0 with Priority: 1
Thread-1 with Priority: 10
Thread-2 with Priority: 5
⚠️ Output ka order har baar alag ho sakta hai, because thread priorities OS pe depend karti hain. Kabhi kabhi low priority thread pehle bhi chal sakta hai.
Note:
Thread priorities 1 to 10 ke beech hoti hain:
Thread.MIN_PRIORITY
= 1Thread.NORM_PRIORITY
= 5Thread.MAX_PRIORITY
= 10
Synchronization – Jab Threads Ek Saath Resource Use Karein
Agar 2 threads ek hi resource (e.g., variable, file) ko access karte hain, to data inconsistency ho sakti hai.
Usko bachane ke liye Java mein synchronized keyword hota hai.
Example:
class Counter {
int count = 0;
synchronized void increment() {
count++;
}
}
Real Use Case – Counting with Threads
class Counter {
int count = 0;
public synchronized void increment() {
count++;
}
}
public class ThreadDemo {
public static void main(String[] args) throws Exception {
Counter c = new Counter();
Thread t1 = new Thread(() -> {
for(int i=0; i<1000; i++) c.increment();
});
Thread t2 = new Thread(() -> {
for(int i=0; i<1000; i++) c.increment();
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Final Count: " + c.count);
}
}
Code Explanation:
class Counter {
int count = 0;
public synchronized void increment() {
count++;
}
}
Yeh kya kar raha hai?
Counter
class mein ek variablecount
hai jo initially 0 hai.increment()
method uscount
ko 1 se increase karta hai.- Lekin important cheez yeh hai:
-
synchronized
keyword ka use kiya gaya hai — iska matlab: - Jab ek thread
increment()
method chala raha hoga, doosra thread us method ko us waqt access nahi kar sakta. - Yeh race condition se bachata hai.
public class ThreadDemo {
public static void main(String[] args) throws Exception {
main()
method yahan se start hota hai, aurException
handle karne ke liyethrows
use hua hai (because ofjoin()
method).
Counter c = new Counter();
- Humne
Counter
class ka ek objectc
banaya.
Thread t1 = new Thread(() -> {
for(int i=0; i<1000; i++) c.increment();
});
Thread t2 = new Thread(() -> {
for(int i=0; i<1000; i++) c.increment();
});
t1
aurt2
do alag threads hain.- Dono thread
1000
baarincrement()
method call karte hain. - Matlab total
2000
increments hone chahiye.
t1.start(); t2.start();
- Yeh dono threads ko start karta hai — ab yeh parallel chalenge.
t1.join();
t2.join();
join()
ka matlab:main()
thread wait karega jab takt1
aurt2
complete na ho jaye.- Warna output wrong ya incomplete ho sakta hai.
System.out.println("Final Count: " + c.count);
- Jab dono threads finish kar lenge, tab hum final count print karte hain.
Expected Output:
Final Count: 2000
Agar synchronized
nahi lagate to kya hota?
- Threads ek hi waqt
count++
ko access kar lete. - Race condition hoti.
- Final output unpredictable hoti (e.g., 1983, 1995, etc.).
- Kyunki
count++
ek atomic operation nahi hai – usmein read + modify + write hota hai.
Tips for Multithreading
- Hamesha shared resource ko synchronize karo.
sleep()
aurjoin()
se execution control mein rakh sakte ho.- Avoid race conditions.
- Threads ke naam
setName()
se bhi set kar sakte ho.
Conclusion
Multithreading Java ka ek powerful concept hai jo real-world applications mein performance boost karta hai. Agar aapko multitasking applications banani hai (jaise games, downloading software, chat apps), to multithreading zaroori hai.
Comments