This article landlord then on the multi-threaded security issues continue to discuss multi-threaded deadlock problem.
We can construct such a scene: the traditional (ideal) case, the landlord must use two chopsticks to eat, and the landlord (American) must use a knife, a fork; now, the landlord has a chopsticks and a knife, the boss has a chopsticks and a fork; when we are waiting for each other to give us the tableware, There are waiting for each other phenomenon, all eat food, thus forming a deadlock.
So in the last article said that the solution of multi-threaded synchronization security problems derived from: if there is a synchronous nesting, it is easy to create a deadlock problem. Above the scene we first use the code to achieve a look.
Build Mylock class, create landlord, boss two lock objects:
1 PackageCom.jon.dielock;2 3 Public classmylock{4 //Create 2 Objects5 Public Static FinalObject Obja =NewObject ();6 Public Static FinalObject OBJB =NewObject ();7}
Create a Dielock class integration thread to build a deadlock scenario (synchronous nesting):
1 PackageCom.jon.dielock;2 3 Public classDielockextendsThread {4 Private BooleanFlag//threads are created with different tags to represent different people5 PublicDielock (Booleanflag) {6 This. Flag =Flag;7 }8 @Override9 Public voidrun () {Ten if(flag) { One synchronized(mylock.obja) { ASystem.out.println ("If Obja"); - synchronized(MYLOCK.OBJB) { -System.out.println ("If OBJB"); the } - } -}Else{ - synchronized(MYLOCK.OBJB) { +System.out.println ("Else OBJB"); - synchronized(mylock.obja) { +System.out.println ("Else Obja"); A } at } - } - } -}
To create a test class Testdielock:
1 PackageCom.jon.dielock;2 3 Public classTestdielock {4 5 Public Static voidMain (string[] args) {6Dielock DL1 =NewDielock (true);7Dielock DL2 =NewDielock (false);8 9 Dl1.start ();Ten Dl2.start (); One } A -}
We run to see the results of the output:
1 Else OBJB 2 if obja
It is obvious that if and else are not finished, ideally all should be output.
The following is also customary to illustrate (assuming the thread DL2 first to grab the CPU execution right):
This scenario forms a deadlock solution The landlord will specify in the next article. This article uses the relevant code address: Https://github.com/LJunChina/JavaResource of the Dielock project.
Multi-threaded deadlock generation