Thread Synchronization in Java
Thread Synchronization
Prevent race conditions when multiple threads access shared resources.
Synchronized Methods
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
// Synchronized block
synchronized(this) {
// Critical section
}Key Points
synchronizedensures only one thread executes at a time.- Synchronized methods vs blocks (finer control).
- Wait/notify for thread communication.
- Deadlock risk with multiple locks.