Use the synchronized keyword to prevent concurrent access to critical sections by multiple threads, ensuring thread safety.
Source Code
class Counter {
private int count = 0;
// Synchronized method to add thread safety
public synchronized void increment() {
count++;
}
}