A simple Java deadlock

Source: Internet
Author: User

In the actual programming, to try to avoid the deadlock situation, but let you deliberately write a deadlock program seems not too simple (there is a company will be such an interview), the following is a simple deadlock example, the program instructions are written in the comments of the class, a bit wordy, but should also be expressed clearly.

[Code=java]

/**
* A simple Deadlock class
* @author IStar
* When the Class object Flag=1 (T1), first lock O1, sleep 500 milliseconds, and then lock O2;
* While T1 during sleep another flag=0 object (T2) thread starts, locks O2, sleeps 500 milliseconds, waits for T1 to release O1;
* T1 sleep After the end of the need to lock O2 to continue execution, and at this time O2 has been T2 locked;
* T2 sleep After the end of the need to lock O1 to continue execution, and at this time O1 has been T1 locked;
* T1, T2 wait for each other, both need the other lock resources to continue execution, thereby deadlock.
*/
Class DeadLock implements Runnable {
public int flag = 1;
Static Object O1 = new Object (), O2 = new Object ();

@Override
public void Run () {
System.out.println ("flag=" + flag);
if (flag = = 1) {
Synchronized (O1) {
try {
Thread.Sleep (500);
} catch (Exception e) {
E.printstacktrace ();
}
Synchronized (O2) {
System.out.println ("1");
}
}
}
if (flag = = 0) {
Synchronized (O2) {
try {
Thread.Sleep (500);
} catch (Exception e) {
E.printstacktrace ();
}
Synchronized (O1) {
System.out.println ("0");
}
}
}
}

public static void Main (string[] args) {
DeadLock TD1 = new DeadLock ();
DeadLock TD2 = new DeadLock ();
Td1.flag = 1;
Td2.flag = 0;
New Thread (TD1). Start ();
New Thread (TD2). Start ();

}
}
[/code]

A simple Java 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.