The deadlock of the JDK thread

Source: Internet
Author: User

Two threads wait for each other to release the Sync Listener, and the deadlock will occur when the other person's results are waiting to be executed.

Male to female said: You marry me first, I buy you a house again, female to Male said: you buy a house for me first, I marry you again.

Multiple threads Lock the same listener at the same time .

Avoid deadlocks in development.

Examples of deadlocks:

 Public classDeadLock { Public Static voidMain (string[] args) {Resource R1=NewResource (); Resource R2=NewResource (); //each thread has a r1,r2 two objectsThread MYTH1 =NewMyThread1 (R1, r2); Thread MYTH2=NewMyThread2 (R1, r2);        Myth1.start ();    Myth2.start (); }}classResource {Private inti;}classMyThread1extendsThread {PrivateResource R1, R2;  PublicMyThread1 (Resource R1, Resource r2) { This. R1 =R1;  This. r2 =R2; } @Override Public voidrun () { while(true) {            //get the lock of R1 first, and then get the lock of R2            synchronized(R1) {System.out.println ("Line Line 1 gets the R1 lock."); synchronized(R2) {System.out.println ("Line Line 1 gets the R2 lock."); }            }        }    }}classMyThread2extendsThread {PrivateResource R1, R2;  PublicMyThread2 (Resource R1, Resource r2) { This. R1 =R1;  This. r2 =R2; } @Override Public voidrun () { while(true) {            //get the lock of R2 first, and then get the lock of R1            synchronized(R2) {System.out.println ("Line Line 2 gets the R2 lock."); synchronized(R1) {System.out.println ("Line Line 2 gets the R1 lock."); }            }        }    }}

The deadlock of the JDK thread

Related Article

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.