The idea is to create two strings A and B, and then create two threads A and b, so that each thread with synchronized lock string (a first lock A, then lock b;b first lock B, then lock a), if a lock a, a, lock b,a there is no way to lock the B,B also can't lock A, then fell into a deadlock. Direct Sticker Code:
1 Public classDeadLock {2 Public StaticString obj1 ="obj1";3 Public StaticString Obj2 ="Obj2";4 Public Static voidMain (string[] args) {5Thread A =NewThread (NewLock1 ());6Thread B =NewThread (NewLock2 ());7 A.start ();8 B.start ();9 } Ten } One classLock1 implements runnable{ A @Override - Public voidrun () { - Try{ theSystem. out. println ("Lock1 Running"); - while(true){ - synchronized (deadlock.obj1) { -System. out. println ("Lock1 Lock Obj1"); +Thread.Sleep ( the);//Get obj1 Wait a moment, let Lock2 have enough time to lock Obj2 - synchronized (deadlock.obj2) { +System. out. println ("Lock1 Lock Obj2"); A } at } - } -}Catch(Exception e) { - e.printstacktrace (); - } - } in } - classLock2 implements runnable{ to @Override + Public voidrun () { - Try{ theSystem. out. println ("Lock2 Running"); * while(true){ $ synchronized (deadlock.obj2) {Panax NotoginsengSystem. out. println ("Lock2 Lock Obj2"); -Thread.Sleep ( the); the synchronized (deadlock.obj1) { +System. out. println ("Lock2 Lock Obj1"); A } the } + } -}Catch(Exception e) { $ e.printstacktrace (); $ } - } -}
Results of the operation:
As you can see, Lock1 gets Obj1,lock2 to get obj2, but none of them have the means to get another obj because they are waiting for the other person to release the lock first, which is the deadlock.
What if we only run Lock1? Modify the main function to comment out thread B.
1 Public classDeadLock {2 Public StaticString obj1 ="obj1";3 Public StaticString Obj2 ="Obj2";4 Public Static voidMain (string[] args) {5Thread A =NewThread (NewLock1 ());6 //thread B = new Thread (new Lock2 ());7 A.start ();8 //B.start ();9 }Ten } One classLock1 implements runnable{ A @Override - Public voidrun () { - Try{ theSystem. out. println ("Lock1 Running"); - while(true){ - synchronized (deadlock.obj1) { -System. out. println ("Lock1 Lock Obj1"); +Thread.Sleep ( the); - synchronized (deadlock.obj2) { +System. out. println ("Lock1 Lock Obj2"); A } at } - } -}Catch(Exception e) { - e.printstacktrace (); - } - } in } - classLock2 implements runnable{ to @Override + Public voidrun () { - Try{ theSystem. out. println ("Lock2 Running"); * while(true){ $ synchronized (deadlock.obj2) {Panax NotoginsengSystem. out. println ("Lock2 Lock Obj2"); -Thread.Sleep ( the); the synchronized (deadlock.obj1) { +System. out. println ("Lock2 Lock Obj1"); A } the } + } -}Catch(Exception e) { $ e.printstacktrace (); $ } - } -}
The result of the operation is:
There is no deadlock because there are no other threads competing with Lock1 for Obj1 and Obj2,lock1 to be able to iterate and release them continuously.
A simple example of how Java generates deadlocks