What is the synchronized method in Java

Antwan picture Antwan · Nov 25, 2013 · Viewed 68.1k times · Source

What is the main idea of synchronized method and synchronized block in Java?

And why should we use them?

Sample code would be nice. I have read the Java documentation about synchronized method, but I didn't get the idea.

This is the Java documentation code

public class SynchronizedCounter {
    private int c = 0;

    public synchronized void increment() {
        c++;
    }

    public synchronized void decrement() {
        c--;
    }

    public synchronized int value() {
        return c;
    }
}

Answer