It is possible that the execution of these two statements is intertwined:
Thread 1: a.methodA(b);
to execute a.methodA() , Thread 1 will have to obtain a lock on object A
to execute b.methodB() , Thread 2 will have to obtain a lock on object B
For Thread 1 methodA() to then call the synchronous method on instance B , it will need to get a lock on B held by Thread 2, which will call Thread 1 until the lock is released.
For Thread2 methodB() , to be able to call the synchronized method on instance A , it will need to get the lock held on A thread 1, which will cause Thread 2 to wait.
Since each thread holds the lock that the other thread wants, a deadlock occurs when no thread can get the required lock and no thread releases the locks that it holds.
It is important to understand that this code will not create a deadlock in 100% of cases when you run it - only when the four key steps (Thread1 holds the lock and tries to get B, which Thread 2 has lock B and tries to get A) are executed in a certain order. Run this code enough times, and this order will happen.
source share