Java: A simple deadlock example

Source: Internet
Author: User

Java: A simple deadlock example

Content: A simple deadlock example, the general idea: two threads A and B, two locks X and Y. Now A gets the lock X first, and then sleep () for A while, we know that sleep () does not release lock resources. Then, if thread B gets the lock Y and sleep () for a period of time, then when both threads wake up, they will wait for each other to release the lock resources and hold off, deadlock. Flag is used to obtain different locks for A and B.

 

Public class TestDeadLock {public void run () {MyThread mt = new MyThread (); new Thread (mt, "James "). start (); new Thread (mt, "Li Si "). start ();} class MyThread implements Runnable {private Object o1 = new Object (); private Object o2 = new Object (); private boolean flag = true; @ Overridepublic void run () {if (flag) {flag = false; synchronized (o1) {System. out. println (Thread. currentThread (). getName () + "have o1"); try {Thread. sleep (100);} catch (InterruptedException e) {e. printStackTrace ();} synchronized (o2) {System. out. println (Thread. currentThread (). getName () + "have o2") ;}} else {flag = true; synchronized (o2) {System. out. println (Thread. currentThread (). getName () + "have o2"); try {Thread. sleep (100);} catch (InterruptedException e) {e. printStackTrace ();} synchronized (o1) {System. out. println (Thread. currentThread (). getName () + "have o1") ;}}} public static void main (String [] args) {new TestDeadLock (). run ();}}


 

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.