fbpx

What is the purpose of the "synchronized" keyword in Java? Provide an example.

public class Example {
    private static int counter = 0;

    public synchronized void increment() {
        // Code inside this block is synchronized
        counter++;
    }
}

 

The "synchronized" keyword in Java is used to control access to critical sections of code, preventing multiple threads from executing them simultaneously. This ensures that only one thread can access the synchronized block at a time, preventing data corruption in shared resources.

# Dream job to realty