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