This article copyright belongs to the distant wind Lyh and the blog garden altogether, welcome reprint, but must retain this paragraph statement, and gives the original text link, thanks cooperation.
Development time is long, will inevitably write some of the code of the deadlock, oneself clearly call this method can be not executed, not into the method, the log does not print!
Here we simulate a deadlock code, using the JDK's own management tool to troubleshoot is not a deadlock!
1 //Thinking about code2 Public classDeadlockdemoImplementsrunnable{3 4 Public intFlag = 1;5 //static objects are shared by all objects of the class6 Private StaticObject O1 =NewObject (), O2 =NewObject ();7 @Override8 Public voidrun () {9System.out.println ("flag=" +flag);Ten if(Flag = = 1) { One synchronized(O1) { A Try { -Thread.Sleep (500); - the}Catch(Exception e) { - e.printstacktrace (); - } - synchronized(O2) { +System.out.println ("1"); - } + } A } at if(flag = = 0) { - synchronized(O2) { - Try { -Thread.Sleep (500); -}Catch(Exception e) { - e.printstacktrace (); in } - synchronized(O1) { toSystem.out.println ("0"); + } - } the } * } $ Panax Notoginseng Public Static voidMain (string[] args) { - theDeadlockdemo TD1 =NewDeadlockdemo (); +Deadlockdemo TD2 =NewDeadlockdemo (); ATd1.flag = 1; theTd2.flag = 0; + //The TD1,TD2 is in an executable state, but it is not certain which thread the JVM thread is scheduled to execute first. - //TD2 Run () may be running before TD1 run () $ NewThread (TD1). Start (); $ NewThread (TD2). Start (); - - } the}
Start the code, after execution has been stuck
Next we use the command JPS in the terminal to query the port number of this class is 7824
Then use the Jstack port number
7824
You can find the deadlock in this section of the program!
Deadlock troubleshooting Tips-using the JDK's own management tools Jstack