Monday, October 17, 2011

Example of Deadlock in Threads

Often we hear of Deadlocks. I tried replicating it using a simple example through threads.
Lets take an example of two people Jack and Jill; trying to exchange business cards.

Rules of exchanging cards
  1. You offer your business card to someone.
  2. The other person accepts your card and gives you his card.


DeadLock

What if both people offer each other cards at the same time? Since both have to follow the rules of exchanging cards, both of them will be stuck in a deadlock since both will wait for the other to accept their cards. (Ignore the case where they offer the card with one hand and accept it with other. Assume that both are one handed)





Java Code to Replicate the Above :
 
 
 
 
Output
Jack : I am giving card to Jill
Jill : I am giving card to Jack

Output if we uncomment the Thread.sleep try block in the code above
Jack : I am giving card to Jill
               Thankyou for your card.Please Accept My Card. My Name is :Jill
Jill : I am giving card to Jack
               Thankyou for your card.Please Accept My Card. My Name is :Jack
    

No comments:

Post a Comment