Thread synchronization--deadlock issues

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.