In practical programming, to avoid the deadlock situation, but let you deliberately write a deadlock program is not too simple (there is a company will be such an interview), the following is a simple deadlock example.
Synchronization of threads can cause deadlocks, and deadlocks occur when two of threads hold each other's waiting items (actually, something that is shared by two threads). Deadlocks can occur as long as there are two threads and two objects.
Package sxh.java.lock;/*** a simple deadlock class * When Deadlock Class object Flag==1 (TD1), lock O1 First, sleep 500 milliseconds * while TD1 in sleep when another Flag==0 object (TD2) thread starts, Lock O2 First, sleep 500 milliseconds * TD1 need to lock O2 after sleep to continue execution, at this time O2 has been td2 locked; * TD2 After the end of sleep need to lock O1 to continue execution, while O1 has been TD1 locked; * TD1, TD2 wait for each other, All need to get the other locked resources to continue execution, thus deadlock. */public class DeadLock implements Runnable {public int flag = 1;//Static object is shared by all objects of the class private static object O1 = new Object (), O2 = new Object (), @Overridepublic Void Run () {System.out.println ("flag=" + flag), if (flag = = 1) {synchronized (O1) {try {T Hread.sleep (500);} catch (Exception e) {e.printstacktrace ();} Synchronized (O2) {System.out.println ("1");}} if (flag = = 0) {synchronized (O2) {try {thread.sleep];} catch (Exception e) {e.printstacktrace ();} Synchronized (O1) {System.out.println ("0");}}} public static void Main (string[] args) {DeadLock TD1 = new DeadLock ();D eadlock td2 = new DeadLock (); td1.flag = 1;td2.flag = 0;//td1,td2 are all in the executable state, but it is not certain which thread the JVM thread is scheduled to execute first. TD2 's Run () may run the new thread (TD1) before TD1 Run (). Start (); new Thread (TD2). Start ();}}
A simple example of a Java deadlock