Java Multi-threaded deadlock

Source: Internet
Author: User

Deadlock cases:

 Packagecom.test; Public classDealthreadImplementsRunnable { PublicString username;  PublicObject Lock1 =NewObject ();  PublicObject Lock2 =NewObject ();  Public voidSetflag (String username) { This. Username =username; } @Override Public voidrun () {if(Username.equals ("a")) {            synchronized(lock1) {Try{System.out.println ("Username =" +username); Thread.Sleep (3000); } Catch(Exception e) {e.printstacktrace (); }                synchronized(Lock2) {System.out.println ("Executed by LOCK1, Lock2 code Order"); }            }        }        if(Username.equals ("B")) {            synchronized(lock2) {Try{System.out.println ("Username =" +username); Thread.Sleep (3000); } Catch(Exception e) {e.printstacktrace (); }                synchronized(lock1) {System.out.println ("Executed by Lock2, Lock1 code Order"); }            }        }    }}
 Packagecom.test; Public classRun { Public Static voidMain (string[] args) {Try{dealthread D1=NewDealthread (); D1.setflag (A); Thread Thread1=NewThread (D1);            Thread1.start (); Thread.Sleep (100); D1.setflag ("B"); Thread thread2=NewThread (D1);        Thread2.start (); } Catch(Exception e) {e.printstacktrace (); }    }}
== b

Deadlock is a programming bug, in the design process to avoid the two sides hold each other lock. This case uses the synchronized nested code structure to implement deadlocks, but it does not apply to nested code structures that can also be deadlocked. Deadlocks can occur as long as you wait for each other to release the lock.

Java Multi-threaded deadlock

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.