Java Inter-Thread Communication
Java provides methods like wait()
, notify()
, and notifyAll()
for communication between threads. These methods must be called inside a synchronized block.
Java wait()
, notify()
, और notifyAll()
जैसे methods देता है जिससे threads आपस में communicate कर सकें। ये methods synchronized block के अंदर ही उपयोग होते हैं।
Example: wait() and notify()
class Bank {
int balance = 5000;
synchronized void withdraw(int amount) {
System.out.println("Trying to withdraw...");
if (balance < amount) {
System.out.println("Insufficient balance. Waiting for deposit...");
try {
wait();
} catch (Exception e) {}
}
balance -= amount;
System.out.println("Withdraw successful! Remaining: " + balance);
}
synchronized void deposit(int amount) {
System.out.println("Depositing...");
balance += amount;
System.out.println("Deposit completed! Balance: " + balance);
notify();
}
}
public class InterThreadExample {
public static void main(String[] args) {
Bank bank = new Bank();
new Thread(() -> bank.withdraw(7000)).start();
new Thread(() -> {
try {
Thread.sleep(2000);
bank.deposit(3000);
} catch (Exception e) {}
}).start();
}
}
Trying to withdraw...
Insufficient balance. Waiting for deposit...
Depositing...
Deposit completed! Balance: 8000
Withdraw successful! Remaining: 1000
Insufficient balance. Waiting for deposit...
Depositing...
Deposit completed! Balance: 8000
Withdraw successful! Remaining: 1000
This program demonstrates how one thread waits for the balance and the other thread notifies after depositing.
यह प्रोग्राम दिखाता है कि एक थ्रेड बैलेंस का इंतज़ार करता है और दूसरा थ्रेड डिपॉज़िट करके notify करता है।