vivek dhiman wrote:
From the above code Can we say that Deadlock occuring? If yes the why? Thankx
The above code may reach a deadlock state..
You see the order of synchronized block in both the threads.
1). 1st
thread gets lock on d, and when it calls Thread.sleep(50), the second thread may get the CPU and it gets the lock on d1.
Now, again 2nd thread calls Thread.sleep(50).
2). At this point, it may be possible that, 1st thread can get the CPU, in which case, it will try to get lock on d1, but can't get it... So, it goes into Waiting State.
Again, 2nd thread may get the CPU, and will try to get lock on d, which is still with 1st thread... So, it will also go to waiting state.
So, both the threads will continuously get CPU and go to waiting state, thus leading into a Deadlock.
3). Now, suppose in point (1), When thread 1 goes to sleep, CPU is not allotted to thread 2, rather to a different thread. So, there is an equal chance for both threads to get CPU later on when it is free..
So, if thread 1 again gets the CPU, then in this case deadlock will not occur, because, it will try to get lock on d1, which is free..
THAT's IT