Thread thdB = new Thread(r2);
Listing 4-28 's thread A and thread B call instanceMethod1() and in-
stanceMethod2() , respectively, at different times. Consider the following execu-
1. Thread A calls instanceMethod1() , obtains the lock assigned to the
lock1 -referenced object, and enters its outer critical section (but has not yet
acquired the lock assigned to the lock2 -referenced object).
2. Thread B calls instanceMethod2() , obtains the lock assigned to the
lock2 -referenced object, and enters its outer critical section (but has not yet
acquired the lock assigned to the lock1 -referenced object).
3. ThreadAattemptstoacquirethelockassociatedwith lock2 .TheJVMforces
the thread to wait outside of the inner critical section because thread B holds
4. ThreadBattemptstoacquirethelockassociatedwith lock1 .TheJVMforces
the thread to wait outside of the inner critical section because thread A holds
have a deadlock situation and the program (at least in the context of the two
threads) freezes up.
easy to detect deadlock. For example, your code might contain the following circular
relationship among various classes (in several source files):
• Class A's synchronized method calls class B's synchronized method.
• Class B's synchronized method calls class C's synchronized method.
• Class C's synchronized method calls class A's synchronized method.
and thread A is still inside of that method. Thread A will continue to execute until it
calls class C's synchronized method, and then block. Deadlock results.