Thread Synchronization in Java
Synchronization in Java is used to control access to shared resources by multiple threads. Without synchronization, it is possible for one thread to modify a shared resource while another thread is in the process of using or updating it. This can lead to inconsistent or incorrect results.
Java में Synchronization का उपयोग shared resources तक एक से अधिक threads की पहुंच को नियंत्रित करने के लिए किया जाता है। अगर synchronization न हो तो एक thread किसी resource को modify कर सकता है जब कि दूसरा thread उसी resource को उपयोग या update कर रहा हो, जिससे गलत परिणाम आ सकते हैं।
Why is Synchronization Needed?
- To prevent thread interference
- To ensure thread safety
- To avoid data inconsistency
- Thread interference रोकने के लिए
- Thread safety सुनिश्चित करने के लिए
- Data inconsistency से बचने के लिए
Example: Deposit Amount in Joint Bank Account
class Bank {
private int balance = 1000;
synchronized void deposit(int amount) {
balance += amount;
System.out.println(Thread.currentThread().getName() + " deposited: " + amount + ", Balance: " + balance);
}
}
class Customer extends Thread {
Bank account;
Customer(Bank account, String name) {
super(name);
this.account = account;
}
public void run() {
account.deposit(500);
}
}
public class SyncExample {
public static void main(String[] args) {
Bank sharedAccount = new Bank();
Customer c1 = new Customer(sharedAccount, "Alice");
Customer c2 = new Customer(sharedAccount, "Bob");
c1.start();
c2.start();
}
}
Expected Output
Alice deposited: 500, Balance: 1500
Bob deposited: 500, Balance: 2000
Both threads safely deposited to the shared account without interfering with each other, thanks to the synchronized
method.
दोनों threads ने सुरक्षित रूप से shared account में पैसे जमा किए बिना interference के, क्योंकि synchronized
method का उपयोग किया गया।