If i synchronized two methods on the same class, can they run simultaneously?

Shelef picture Shelef · Mar 15, 2013 · Viewed 70.3k times · Source

If i synchronized two methods on the same class, can they run simultaneously on the same object? for example:

class A {
    public synchronized void methodA() {
        //method A
    }

    public synchronized void methodB() {
        // method B
    }
}

I know that I can't run methodA() twice on same object in two different threads. same thing in methodB().

But can I run methodB() on different thread while methodA() is still running? (same object)

Answer

NPE picture NPE · Mar 15, 2013

Both methods lock the same monitor. Therefore, you can't simultaneously execute them on the same object from different threads (one of the two methods will block until the other is finished).