What is the synchronized method in Java [duplicate]
Asked Answered
N

0

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;
    }
}
Nassir answered 25/11, 2013 at 1:12 Comment(1)
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.Oma

© 2022 - 2024 — McMap. All rights reserved.