public class SynchronizedMethodExample {
// Synchronized method prevents concurrent access
public synchronized void criticalMethod() {
// Only one thread can execute this method at a time
// Shared resource modifications happen here
}
// Alternative explicit synchronization
public void explicitSyncMethod() {
synchronized(this) {
// Synchronized block with same effect
}
}
}
public class SynchronizedBlockExample {
private final Object lock = new Object();
private int sharedResource;
public void modifyResource() {
// Synchronized block with custom lock object
synchronized(lock) {
// Critical section
sharedResource++;
}
}
}
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicOperationExample {
private AtomicInteger counter = new AtomicInteger(0);
public void incrementCounter() {
// Atomic increment operation
counter.incrementAndGet();
}
public int getCounterValue() {
return counter.get();
}
}