Showing posts with label multithreading in java. Show all posts
Showing posts with label multithreading in java. Show all posts

Tuesday, July 29, 2025

Java Synchronization जावा में सिंक्रोनाइजेशन

Synchronization in Java is a technique used to control the access of multiple threads to a shared resource. When multiple threads try to access the same method or resource simultaneously, it may lead to inconsistency or unexpected behavior. Synchronization ensures that only one thread can access the resource at a time.

जावा में सिंक्रोनाइजेशन एक ऐसी तकनीक है जिसका उपयोग तब किया जाता है जब एक से अधिक थ्रेड किसी साझा संसाधन (resource) को एक ही समय पर एक्सेस करने की कोशिश करते हैं। यह स्थिति डेटा इनकंसिस्टेंसी या प्रोग्राम एरर का कारण बन सकती है। सिंक्रोनाइजेशन के द्वारा हम सुनिश्चित करते हैं कि एक समय में केवल एक ही थ्रेड उस संसाधन को एक्सेस करे।


🧵 Why Synchronization is Needed? (सिंक्रोनाइजेशन क्यों आवश्यक है?)

English:

  • Prevents thread interference थ्रेड हस्तक्षेप को रोकने के लिए

  • Ensures data consistency डेटा की स्थिरता बनाए रखने के लिए

  • Useful in banking apps, inventory systems, etc. बैंकिंग या इन्वेंट्री जैसे एप्लिकेशन में आवश्यक


🛠️ Ways to Synchronize in Java (जावा में सिंक्रोनाइजेशन के तरीके)

1️⃣ Synchronized Method (सिंक्रोनाइज्ड मेथड)

You can synchronize an entire method by adding the synchronized keyword to its declaration. This locks the resource for that thread.

आप किसी मेथड को पूरी तरह से synchronized बना सकते हैं। इसके लिए synchronized कीवर्ड को मेथड डिक्लेरेशन में जोड़ा जाता है। इससे वह मेथड उस थ्रेड के लिए लॉक हो जाता है।

Syntax:

synchronized return_type methodName() {
// critical section
}

2️⃣ Synchronized Block (सिंक्रोनाइज्ड ब्लॉक)

If only part of the method needs to be synchronized, you can use a synchronized block to lock only that section.

यदि पूरे मेथड को synchronized बनाना आवश्यक न हो तो केवल उस भाग को लॉक किया जा सकता है जहाँ साझा संसाधन उपयोग हो रहा हो।

Syntax:

synchronized(object_reference) {
// critical code
}

🧪 Example: Synchronized Method

Below is a Java program that uses a synchronized method to print a multiplication table safely when accessed by two threads:

English:
This example shows that even if two threads call the same method on the same object, the output remains consistent.

Hindi:
यह उदाहरण दर्शाता है कि दो थ्रेड्स यदि एक ही ऑब्जेक्ट की मेथड को कॉल करें, तब भी आउटपुट बिना टकराव के आता है।

// Java Program to demonstrate synchronized method
class Table {
synchronized void printTable(int n) {
for (int i = 1; i <= 10; i++) {
System.out.println(n * i);
try {
Thread.sleep(400);
} catch (Exception e) {
System.out.println(e);
}
}
}
}
public class TestSynchronization {
public static void main(String args[]) {
final Table obj = new Table(); // shared object
Thread t1 = new Thread() {
public void run() {
obj.printTable(5);
}
};
Thread t2 = new Thread() {
public void run() {
obj.printTable(100);
}
};
t1.start();
t2.start();
}
}

Output (आउटपुट):

5
10
15
...
50
100
200
300
...
1000

📝 Output always comes in a sequence – either full 5-table or full 100-table first, never mixed — thanks to synchronization.


🔐 Benefits of Synchronization (सिंक्रोनाइजेशन के लाभ)

✅ Thread-safe resource access थ्रेड-सेफ संसाधन एक्सेस
✅ Avoids race conditions रेस कंडीशन से सुरक्षा
✅ Suitable for multi-user systems मल्टी-यूज़र सिस्टम में उपयोगी
✅ Reduces inconsistent state errors डेटा असंगतता से बचाव



⚠️ Caution While Using Synchronization (सावधानी)

English:
Overusing synchronization may cause: सिंक्रोनाइजेशन का अत्यधिक उपयोग कर सकते हैं:

  • Performance degradation परफॉर्मेंस में कमी

  • Deadlocks if not handled carefully डेडलॉक की संभावना


🔚 Conclusion (निष्कर्ष)

Synchronization is a vital part of multithreaded programming in Java. It helps maintain consistency and correctness in concurrent applications by allowing only one thread to access a resource at a time.

सिंक्रोनाइजेशन जावा की मल्टीथ्रेडिंग का एक अनिवार्य हिस्सा है। यह एक समय में केवल एक थ्रेड को साझा संसाधन तक पहुंच प्रदान कर प्रोग्राम को सुरक्षित और सटीक बनाता है।

Java Multithreading जावा में मल्टीथ्रेडिंग

Multithreading in Java is a powerful feature that allows concurrent execution of two or more parts of a program to make the best use of CPU. Java enables programs to perform multiple tasks simultaneously using threads.

जब हम जावा प्रोग्राम चलाते हैं, तो CPU को कई बार इंतजार करना पड़ता है जैसे – इनपुट लेने में, नेटवर्क रिस्पॉन्स का इंतजार, या कोई अन्य प्रोसेस के कारण। इस बेकार समय का उपयोग हम दूसरे कार्यों के लिए कर सकते हैं, और यही प्रक्रिया Multithreading कहलाती है।


🧵 What is a Thread? (थ्रेड क्या होता है?)

A Thread is a lightweight subprocess, the smallest unit of processing. A thread executes within a program and shares process resources with other threads.

एक थ्रेड वह यूनिट है जो "execution में चल रहा प्रोग्राम" कहलाता है। जावा प्रोग्राम में default thread main() होता है। लेकिन हम और भी थ्रेड्स बना सकते हैं ताकि काम समानांतर (parallel) हो सके।


🔄 Thread Life Cycle (थ्रेड का जीवन चक्र)

  1. New – Thread is created. थ्रेड ऑब्जेक्ट बनते ही इस स्थिति में होता है।

  2. Runnable – Thread is ready to run. start() मेथड कॉल होने पर Runnable स्थिति में आता है।

  3. Running – Thread is executing.  run() मेथड कॉल होने पर यह एक्टिव होता है।

  4. Waiting – Thread is waiting for resources.  किसी कारण थ्रेड रुका हुआ है।

  5. Terminated – Thread has completed execution. कार्य समाप्त होते ही थ्रेड Destroy हो जाता है।


🔧 Creating Thread in Java (जावा में थ्रेड बनाना)

1️⃣ Using Thread Class (थ्रेड क्लास का उपयोग)

English:
You can create a thread by extending the Thread class and overriding the run() method.

Hindi:
आप Thread क्लास को extend करके और run() मेथड को override करके थ्रेड बना सकते हैं।

🧪 Example Program:

// Example using Thread class
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running using Thread class.");
}
public static void main(String args[]) {
MyThread t1 = new MyThread();
t1.start(); // Start the thread
}
}

Output:

Thread is running using Thread class.

2️⃣ Using Runnable Interface (रनेबल इंटरफेस का उपयोग)

English:
You can implement the Runnable interface and pass it to the Thread constructor.

Hindi:
आप Runnable इंटरफेस को implement करके उसे Thread के कंस्ट्रक्टर में पास कर सकते हैं।

🧪 Example Program:

// Example using Runnable interface
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running using Runnable interface.");
}
public static void main(String args[]) {
MyRunnable myRunnable = new MyRunnable();
Thread t1 = new Thread(myRunnable);
t1.start(); // Start the thread
}
}

Output:

Thread is running using Runnable interface.

🛠️ Important Thread Methods (महत्वपूर्ण थ्रेड मेथड्स)

Method Description (English) विवरण (Hindi)
start() Starts the thread थ्रेड को चालू करता है
run() Contains the code to be executed थ्रेड द्वारा किया जाने वाला कार्य
sleep(ms) Puts thread to sleep for milliseconds थ्रेड को कुछ समय तक सुलाता है
join() Waits for another thread to die दूसरे थ्रेड के समाप्त होने का इंतजार
getName() Gets thread name थ्रेड का नाम प्राप्त करता है
getPriority() Gets thread priority थ्रेड की प्राथमिकता दर्शाता है
isAlive() Checks if thread is alive थ्रेड ज़िंदा है या नहीं

🧠 Why Use Multithreading in Java? (जावा में मल्टीथ्रेडिंग क्यों?)

✅ Better CPU Utilization (बेहतर CPU उपयोग)
✅ Faster Execution (तेजी से एक्सीक्यूशन)
✅ Efficient Resource Handling (प्रभावी संसाधन उपयोग)
✅ Useful for Games, Servers, GUI Apps (खासकर गेम, सर्वर और GUI के लिए)


📝 निष्कर्ष (Conclusion)

Multithreading makes Java powerful and efficient. By creating multiple threads, a program can utilize system resources better and provide faster execution.

मल्टीथ्रेडिंग से जावा और भी ज्यादा प्रभावी और शक्तिशाली बनता है। यह सीपीयू के समय का बेहतर उपयोग करता है और आपकी एप्लिकेशन को responsive बनाता है।

📚 Other Stream Classes in Java जावा में अन्य स्ट्रीम क्लासेस

In Java, apart from basic byte and character streams, there are several specialized stream classes that provide advanced input-output operat...