Java A simple deadlock example

Source: Internet
Author: User

Content: A simple deadlock example, the approximate idea: two threads A and B, two locks x and Y, now a lock x, and then sleep () for a period of time, we know that sleep () does not release the lock resource. Then if this time thread B get lock Y, also sleep () for a period of time, then wait until two threads wake up, then will wait for each other to release the lock resources and deadlock, into a deadlock. The role of flag is to get a and b different locks.

public class Testdeadlock {public void run () {MyThread MT = new MyThread (); new Thread (MT, "Zhang San"). Start (); New Thread (MT, "John Doe "). Start ();}  Class MyThread implements Runnable {private Object O1 = new Object ();p rivate Object O2 = new Object ();p rivate boolean flag = true; @Overridepublic void Run () {if (flag) {flag = false;synchronized (O1) {System.out.println (Thread.CurrentThread ()). GetName () + "have O1"), try {thread.sleep (+),} catch (Interruptedexception e) {e.printstacktrace ();} Synchronized (O2) {System.out.println (Thread.CurrentThread (). GetName () + "has O2");}}} else {flag = true;synchronized (O2) {System.out.println (Thread.CurrentThread (). GetName () + "has O2"); try {Thread.Sleep (100);} catch (Interruptedexception e) {e.printstacktrace ();} Synchronized (O1) {System.out.println (Thread.CurrentThread (). GetName () + "has O1");}}}} public static void Main (string[] args) {new Testdeadlock (). Run ();}}


Java A simple deadlock example

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.