Is lesson me hum seekhenge:
- Thread Communication kya hota hai
- wait(), notify(), notifyAll()
- Producer-Consumer problem
- Important rules aur examples
Thread communication ka matlab:
multiple threads ka ek dusre ke saath coordinate karna
Example:
ek thread wait kare jab tak dusra kaam complete na kare
Agar threads coordinate na kare:
data inconsistency ya wrong execution ho sakta hai
Java me communication ke liye 3 methods:
wait()
notify()
notifyAll()
Ye methods:
Object class ke hote hain
thread ko wait state me bhej deta hai
wait();✔ lock release karta hai
✔ dusra thread ka wait karta hai
ek waiting thread ko jagata hai
notify();sab waiting threads ko jagata hai
notifyAll();✔ wait(), notify(), notifyAll() sirf:
synchronized block ya method ke andar use hote hain
Real example:
Producer → data banata hai
Consumer → data use karta hai
class Shared {
int data;
boolean available = false;
synchronized void produce(int value) throws Exception {
if(available){
wait();
}
data = value;
available = true;
System.out.println("Produced: " + data);
notify();
}
synchronized void consume() throws Exception {
if(!available){
wait();
}
System.out.println("Consumed: " + data);
available = false;
notify();
}
}class Test {
public static void main(String[] args){
Shared s = new Shared();
Thread producer = new Thread(() -> {
try {
for(int i = 1; i <= 5; i++){
s.produce(i);
}
} catch(Exception e){}
});
Thread consumer = new Thread(() -> {
try {
for(int i = 1; i <= 5; i++){
s.consume();
}
} catch(Exception e){}
});
producer.start();
consumer.start();
}
}Producer produce karega → notify
Consumer consume karega → notify
Restaurant:
Chef (producer) → food banata hai
Customer (consumer) → food khata hai
✔ wait() lock release karta hai
✔ notify() ek thread ko jagata hai
✔ notifyAll() sabko jagata hai
✔ synchronized required hai
❌ wait() outside synchronized
❌ notify() without condition check
- Thread communication kya hota hai?
- wait() aur sleep() me difference?
- notify() vs notifyAll()?
- Producer-Consumer problem kya hai?
Is lesson me humne seekha:
✔ Thread communication concept
✔ wait(), notify(), notifyAll()
✔ Producer-Consumer example
✔ synchronization rules
Thread communication Java me threads ke beech coordination aur synchronization ke liye use hota hai.