Here, everyone answered with the obvious answer. This is the correct answer, but it is not the only correct answer.
The rule is that two threads cannot synchronize simultaneously on the same object. But does this refer to the same object in both method calls? We canβt say because you didnβt show us the calls. Consider this example:
class Demo { synchronized void method1() { ...do something... } synchronized void method2() { ...do something else... } static void caseA() { final Demo demo = new Demo(); new Thread(new Runnable(){ @Override public void run() { demo.method1(); } }).start(); new Thread(new Runnable(){ @Override public void run() { demo.method2(); } }).start(); } static void caseB() { final Demo demo1 = new Demo(); final Demo demo2 = new Demo(); new Thread(new Runnable(){ @Override public void run() { demo1.method1(); } }).start(); new Thread(new Runnable(){ @Override public void run() { demo2.method2(); } }).start(); } }
In case of A (), calls to demo.method1 () and demo.method2 () cannot overlap, because both calls are synchronized on the same object, but in case of B (), two calls are synchronized in two different instances of the Demo class. In case B (), the call to method1 () and the call to method2 () may overlap.
source share