35

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;
    }
}
Antwan
  • 3,837
  • 9
  • 41
  • 62
  • 3
    It's only important if your application has multiple threads. Only one thread at a time can enter a synchronized method operating on a given instance, and, further, only one thread at a time can enter *any* synchronized method belonging to that instance of the class. But this is just scratching the surface -- if you are going to do substantial multi-threading you need to spend some time studying some good references. – Hot Licks Nov 25 '13 at 01:23

0 Answers0