Dead lock
Only when the T1 thread occupies O1 and exactly also needs to o2,t2 at this time to occupy O2 and exactly also need O1 when the deadlock will appear, (similar to 2 people with two chopsticks to eat, all need each other's chopsticks to eat)
The following code T1 thread occupies O1, and gets to O2 object before releasing O1, and T2 thread takes O2 again to get O1, while O1 is occupied by T1 thread, O2 is occupied by T2 thread, T1 and T2 are waiting indefinitely, there will be deadlock.
Packagejavasimple;/*** Deadlock Demo *@authorHaokui **/ Public classdiesynchronized { Public Static voidMain (string[] args) {/*** Create and start two threads T1, T2. Two threads to share O1, O2 two objects*/Object O1=NewObject (); Object O2=NewObject (); Thread T1=NewThread (NewT1 (O1,O2)); Thread T2=NewThread (NewT2 (O1,O2)); T1.start (); T2.start (); }}//Create two thread classesclassT1ImplementsRunnable {Object O1; Object O2; PublicT1 (Object O1, Object O2) { This. O1 =O1; This. O2 =O2; } Public voidrun () {//lock O1 and O2 synchronized(O1) {Try{Thread.Sleep (1000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } synchronized(O2) {System.out.println ("O2"); } } }}classT2ImplementsRunnable {Object O1; Object O2; PublicT2 (Object O1, Object O2) { This. O1 =O1; This. O2 =O2; } Public voidrun () {synchronized(O2) {Try{Thread.Sleep (1000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } synchronized(O1) {System.out.println ("O1"); } } }}
Note: Concurrency occurs only when O1 and O2 are shared, and two objects can be shared by constructors.
Java implementation of deadlock demo