Hi Ani,
Let me give it a try.First of all, I don't think this code is an example for a deadlock condition!My understanding of a dead lock is a situation where a process cannot proceed any further, as a result of which the system hangs.As far as this code is concerned,it works quite clean for both the conditions.
In the first case,since both the threads T1 & T2 synchronise on set() & get() methods via s1 & s2(can I say so?) in the same order,they manage to execute seemingly simultaneously(Actually thread T2 gets active during the time T1 sleeps in the set() & get() method).And hence the output
G:\gudiya\Trials>
java Dead
s2 [T1][T2]
s2 [T1][T2]
s1 [T1][T2]
s1 [T1][T2]
s2 [T1][T2][T1][T2]
s2 [T1][T2][T1][T2]
s1 [T1][T2][T1][T2]
s1 [T1][T2][T1][T2]
s2 [T1][T2][T1][T2][T1][T2]
s2 [T1][T2][T1][T2][T1][T2]
s1 [T1][T2][T1][T2][T1][T2]
s1 [T1][T2][T1][T2][T1][T2]
In the later case,T1's S2 synchronizes on set() and T1's S1 synchronizes on get().During the time T1 sleeps, T2 becomes active and wants to synchronize S1 on set().Now since,T1's S2 has already got the lock on set(),T2 waits till S2's lock on set() is released.
s2.set((Thread.currentThread()).getName(), s1);
After this statement in run(),S2's lock on set() is released and the same locks get().So, now the first S2 [T1] gets printed.What comes next is the two threads alternating locks on set() & get() and printing the updated,appended version of their msg.
G:\gudiya\Trials>java Dead (under deadlock???)
s2 [T1]
s1 [T2][T1]
s1 [T2][T1]
s2 [T1][T2][T1]
s2 [T1][T2][T1]
s1 [T2][T1][T2][T1]
s1 [T2][T1][T2][T1]
s2 [T1][T2][T1][T2][T1]
s2 [T1][T2][T1][T2][T1]
s1 [T2][T1][T2][T1][T2][T1]
s1 [T2][T1][T2][T1][T2][T1]
s2 [T1][T2][T1][T2][T1][T2][T1]
s2 [T1][T2][T1][T2][T1][T2][T1]
I know the output isn't a very pretty sight.But remember, this is just a sample!!!
If you wanna get the feel of a real deadlock condition refer Shailendra Guggali's post
" Threads and Deadlock - a question in
SCJP exam" posted February 04, 2001 12:07 AM
Disclaimer
*********
The output MAY not be the same on your machine!!!