📘 Lesson  ·  Lesson 36

Synchronization

Synchronization

Why Synchronization?

When multiple threads change the same data, results can be wrong. synchronized lets only one thread access a block/method at a time.

synchronized Method

class Counter {
    private int count = 0;
    synchronized void increment() {   // only one thread at a time
        count++;
    }
    int get() { return count; }
}

Thread Safety

Without synchronization, two threads incrementing together can lose updates. synchronized prevents this "race condition".

Summary

  • synchronized allows only one thread into a block/method at a time.
  • It prevents race conditions and makes code thread-safe.

Synchronization क्यों?

जब कई threads एक ही data बदलते हैं, results गलत हो सकते हैं। synchronized एक समय में सिर्फ एक thread को block/method access करने देता है।

synchronized Method

class Counter {
    private int count = 0;
    synchronized void increment() {   // एक समय एक thread
        count++;
    }
    int get() { return count; }
}

Thread Safety

Synchronization बिना, साथ increment करते दो threads updates खो सकते हैं। synchronized इस "race condition" को रोकता है।

सारांश

  • synchronized एक समय एक thread को block/method में जाने देता है।
  • यह race conditions रोकता है और code thread-safe बनाता है।
← Back to Java Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

\n