Java Technologies Thread Synchronization Example: Multiple Thread Access এর মধ্যে Synchronization গাইড ও নোট

403

Thread synchronization in Java ensures that only one thread can access a critical section of code at a time, thus preventing data inconsistency when multiple threads are involved.

Here is an example demonstrating thread synchronization in Java where multiple threads access a shared resource.

Java Example: Thread Synchronization

class Counter {
    private int count = 0;

    // Synchronized method to ensure only one thread can access this at a time
    public synchronized void increment() {
        count++;
    }

    public int getCount() {
        return count;
    }
}

class MyThread extends Thread {
    private Counter counter;

    public MyThread(Counter counter) {
        this.counter = counter;
    }

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            counter.increment();
        }
    }
}

public class SynchronizationExample {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();

        // Creating two threads that will access the same Counter object
        MyThread thread1 = new MyThread(counter);
        MyThread thread2 = new MyThread(counter);

        // Starting both threads
        thread1.start();
        thread2.start();

        // Waiting for both threads to finish
        thread1.join();
        thread2.join();

        // Printing the final count
        System.out.println("Final count: " + counter.getCount());
    }
}

Explanation:

  • Counter class: This class contains a shared resource (count). The method increment() is synchronized to ensure that only one thread can increment the count at a time.
  • MyThread class: This thread class performs the increment operation on the Counter object.
  • Synchronization: The increment() method is synchronized, meaning when one thread is executing it, other threads must wait until the current thread finishes.
  • Main method: Two threads (thread1 and thread2) are created and started. After both threads finish executing, the final value of count is printed.

Output Example:

Final count: 2000

Without synchronization, there could be a race condition where multiple threads update count simultaneously, leading to incorrect results. The synchronized keyword prevents this issue by allowing only one thread to execute the critical section at a time.

Content added By
Promotion

Are you sure to start over?

Loading...