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