Java implementation of deadlock demo

Source: Internet
Author: User

Dead lock

Only when the T1 thread occupies O1 and exactly also needs to o2,t2 at this time to occupy O2 and exactly also need O1 when the deadlock will appear, (similar to 2 people with two chopsticks to eat, all need each other's chopsticks to eat)

The following code T1 thread occupies O1, and gets to O2 object before releasing O1, and T2 thread takes O2 again to get O1, while O1 is occupied by T1 thread, O2 is occupied by T2 thread, T1 and T2 are waiting indefinitely, there will be deadlock.

 Packagejavasimple;/*** Deadlock Demo *@authorHaokui **/ Public classdiesynchronized { Public Static voidMain (string[] args) {/*** Create and start two threads T1, T2. Two threads to share O1, O2 two objects*/Object O1=NewObject (); Object O2=NewObject (); Thread T1=NewThread (NewT1 (O1,O2)); Thread T2=NewThread (NewT2 (O1,O2));        T1.start ();    T2.start (); }}//Create two thread classesclassT1ImplementsRunnable {Object O1;    Object O2;  PublicT1 (Object O1, Object O2) { This. O1 =O1;  This. O2 =O2; }     Public voidrun () {//lock O1 and O2        synchronized(O1) {Try{Thread.Sleep (1000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }            synchronized(O2) {System.out.println ("O2"); }        }    }}classT2ImplementsRunnable {Object O1;    Object O2;  PublicT2 (Object O1, Object O2) { This. O1 =O1;  This. O2 =O2; }     Public voidrun () {synchronized(O2) {Try{Thread.Sleep (1000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }            synchronized(O1) {System.out.println ("O1"); }        }            }}

Note: Concurrency occurs only when O1 and O2 are shared, and two objects can be shared by constructors.

Java implementation of deadlock demo

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.