Sunday 15 August 2010

multithreading - How this java code produces deadlock? -


I'm going through Oracle docs for Deadlock .. I got this code

 < Code> Public class deadlock {Fixed class friend {Private last string name; Public friend (string name) {this.name = name; } Public string getName () {this.name; } Public Synchronized Zero Bow (Make Friend) {System.out.format ("% s:% s" + "Hooked me!% N", this.name, bower.getName ()); Bower.bowBack (this); } Public Synchronized Zero Bow (Make Friend) {System.out.format ("% s:% s" + "Tilted me back!% N", this.name, bower.getName ()); }} Public static zero chief (string [] args) {last friend alphonse = new friend ("Alphonse"); Last friend Gaston = new friend ("Gaston"); New thread (new runleball) (public zero-zero) {alphonse.bow (Gaston);}}) Start (); New thread (new runnable () {public goes zero () {gastrin.bo (alphonse);}}) Start (); }}   

I failed to understand, in which case would the deadlock be?

I run this code, it works fine. So what should be a special event, when the deadlock will occur?

Suppose the bow is called first on the alphance object, should it be the alphanace object when bower.bowBack (this) < / Code> is called the object on the brink? Because if you retain its lock, leave << code> Alpha << code> to lock, and this will never be a catastrophic state

If you put the thread first (1000) after printing the first line and before calling for calling You should see a deadlock. This deadlock can happen in any way, it will be rare.

You have two threads and two lock orders are different. It can leave each thread on one lock but is unable to get another lock. That is a deadlock.

Note: It takes a lot of time to start the thread, which means that the first thread can be completed before the second part starts, so it is unlikely that you will see the problem.


This is a puzzler for you. It makes a standoff, can you see why?

  class A {static last int i; Stable {i = 128; Thread T = new thread () {Public running zero () {System.out.println ("i =" + i); }}; T.start (); Try {t.join (); } Grip (Interrupted E) E. {Thread.currentThread (). Interrupt (); }}    

No comments:

Post a Comment