What is the synchronized method in Java [duplicate

2019-01-22 11:13发布

问题:

This question already has an answer here:

  • What does 'synchronized' mean? 15 answers
  • Learning Java, use of synchronized keyword 2 answers

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;
    }
}