Java - Threads Part 3: Thread Synchronization
Synchronization ensures that multiple threads do not interfere with each other while accessing shared resources.
Examples and Explanation
Synchronized Method
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) counter.increment();
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) counter.increment();
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Final count: " + counter.getCount());
}
}
Explanation: Synchronization prevents race conditions by allowing only one thread at a time to access the critical section.
Synchronized Block
class Counter {
private int count = 0;
public void increment() {
synchronized (this) {
count++;
}
}
public int getCount() {
return count;
}
}
Explanation: Synchronized blocks are more granular, allowing finer control over synchronization.
Static Synchronization
class Shared {
public static synchronized void display(String message) {
System.out.println(message);
}
}
public class Main {
public static void main(String[] args) {
Thread t1 = new Thread(() -> Shared.display("Hello from Thread 1"));
Thread t2 = new Thread(() -> Shared.display("Hello from Thread 2"));
t1.start();
t2.start();
}
}
Explanation: Static synchronization ensures that a single thread can execute a static synchronized method at a time.