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 methodincrement()is synchronized to ensure that only one thread can increment thecountat a time. - MyThread class: This thread class performs the increment operation on the
Counterobject. - 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 (
thread1andthread2) are created and started. After both threads finish executing, the final value ofcountis 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
Read more
Thread Creation Example: Thread তৈরি এবং Runnable Interface ব্যবহার
Inter-thread Communication Example: wait(), notify(), এবং notifyAll() এর ব্যবহার
Deadlock Example: Deadlock কিভাবে কাজ করে এবং এটি কিভাবে প্রতিরোধ করা যায়
Thread Pool Example: Thread Pool ব্যবহার করে Multithreading এর কার্যক্ষমতা বৃদ্ধি