Deadlock Example program: ThreadTest, which is a classic example of a deadlock that occurs with synchronous nesting;
Public classThreadTest { Public StaticObject Lock1 =NewObject (); Public StaticObject Lock2 =NewObject (); Public Static voidmethod1 () {Trace ("Inside method1"); synchronized(lock1) {Trace ("Method1 got Lock1"); DoSomething (); synchronized(Lock2) {Trace ("Method1 got Lock2, sleeping"); DoSomething (); Trace ("Method1 Returning"); } } } Public Static voidmethod2 () {Trace ("Inside method2"); synchronized(Lock2) {Trace ("Method2 got Lock2"); DoSomething (); synchronized(lock1) {Trace ("Method2 got Lock1, sleeping"); DoSomething (); Trace ("Method2 Returning"); } } } Public Static voiddosomething () {Try{Thread.Sleep (5*1000); } Catch(Interruptedexception x) {x.printstacktrace (); } Trace ("Waiking Up"); } Public Static voidTrace (String msg) {System.out.println (Thread.CurrentThread ()+ " : " +msg); } Public Static voidMain (string[] args)throwsException {NewThread (NewRunnable () { Public voidrun () {method1 (); }}). Start (); NewThread (NewRunnable () { Public voidrun () {method2 (); }}). Start (); }}
View Code
Run:
You can see that two threads have been blocked;
To view the current lock view:
Right-click Export:
You can see the text description of the thread blocking situation;
Deadlock unlock cheats are to obtain the order of the locks to remain consistent;
Improve performance by using Jprofile to study thread allocation and synchronization to uncover deadlock and data contention issues