1. Questions
1.1 Reasons for the production
The system has two threads running, each thread has two locks, when the line Cheng with the lock 1, this time the JVM calls the thread two with the lock 2, this time the thread two can not open lock 1, the program has been parked here
1.2 Specific questions
There are two people Aman and Bman to perform the assassination mission, as two threads, the boss there is only a dagger, to assassinate only one person. Aman got the dagger, ready to pick up the assassination mission, but the mission was Bman. Aman did not take the assassination mission, cannot assassinate. Bman without a dagger, unable to complete the assassination
1.3 Solutions
It is recommended not to use nested synchronized
2. Code
1 Public classDemo {2 Public Static voidMain (string[] args) {3String S1 = "Dagger";4String s2 = "Assassination";5 NewThread () {6 7 @Override8 Public voidrun () {9 while(true) {Ten synchronized(S1) { OneSystem.out.println ( This. GetName () + "Get Dagger" + "ready to assassinate"); A synchronized(S2) { -System.out.println ( This. GetName () + "assassination"); - } the } - } - } - + }.start (); - + NewThread () { A at @Override - Public voidrun () { - while(true) { - synchronized(S2) { -System.out.println ( This. GetName () + "Get Dagger" + "ready to assassinate"); - synchronized(S1) { inSystem.out.println ( This. GetName () + "assassination"); - } to } + } - } the * }.start (); $ }Panax Notoginseng}
Thread synchronization--deadlock issues