Is lesson me hum seekhenge:
- Synchronization kya hota hai
- Race condition kya hota hai
- synchronized keyword ka use
- Method aur block synchronization
- Real examples
Synchronization ka matlab:
multiple threads ko ek shared resource ko safe tarike se access karne dena
Jab multiple threads ek hi data ko modify karte hain:
unexpected result milta hai
Example:
Bank balance update
class Counter {
int count = 0;
void increment(){
count++;
}
}Multiple threads call kare:
result incorrect ho sakta hai
class Counter {
int count = 0;
synchronized void increment(){
count++;
}
}✔ ek time par ek thread hi access karega
synchronized void methodName(){
}void method(){
synchronized(this){
// critical section
}
}✔ better performance (poora method lock nahi hota)
class Counter {
int count = 0;
synchronized void increment(){
count++;
}
}
class Test {
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(c.count);
}
}Output:
2000 (correct)
random value (like 1700, 1800)
static synchronized void method(){
}✔ class-level lock
code ka wo part jahan shared resource access hota hai
ek thread lock le leta hai → dusre wait karte hain
✔ data consistency
✔ thread safety
✔ race condition avoid
❌ performance slow ho sakta hai
❌ deadlock ka risk
ATM machine
Ek time par ek hi person use karta hai.
- Synchronization kya hota hai?
- Race condition kya hota hai?
- synchronized method vs block?
- deadlock kya hota hai?
Is lesson me humne seekha:
✔ Synchronization concept
✔ Race condition problem
✔ synchronized keyword
✔ method aur block synchronization
✔ thread safety
Synchronization Java me multi-threaded environment me safe data handling ke liye use hota hai.