Deadlock cases:
Packagecom.test; Public classDealthreadImplementsRunnable { PublicString username; PublicObject Lock1 =NewObject (); PublicObject Lock2 =NewObject (); Public voidSetflag (String username) { This. Username =username; } @Override Public voidrun () {if(Username.equals ("a")) { synchronized(lock1) {Try{System.out.println ("Username =" +username); Thread.Sleep (3000); } Catch(Exception e) {e.printstacktrace (); } synchronized(Lock2) {System.out.println ("Executed by LOCK1, Lock2 code Order"); } } } if(Username.equals ("B")) { synchronized(lock2) {Try{System.out.println ("Username =" +username); Thread.Sleep (3000); } Catch(Exception e) {e.printstacktrace (); } synchronized(lock1) {System.out.println ("Executed by Lock2, Lock1 code Order"); } } } }}
Packagecom.test; Public classRun { Public Static voidMain (string[] args) {Try{dealthread D1=NewDealthread (); D1.setflag (A); Thread Thread1=NewThread (D1); Thread1.start (); Thread.Sleep (100); D1.setflag ("B"); Thread thread2=NewThread (D1); Thread2.start (); } Catch(Exception e) {e.printstacktrace (); } }}
== b
Deadlock is a programming bug, in the design process to avoid the two sides hold each other lock. This case uses the synchronized nested code structure to implement deadlocks, but it does not apply to nested code structures that can also be deadlocked. Deadlocks can occur as long as you wait for each other to release the lock.
Java Multi-threaded deadlock