Java: A simple deadlock example
Content: A simple deadlock example, the general idea: two threads A and B, two locks X and Y. Now A gets the lock X first, and then sleep () for A while, we know that sleep () does not release lock resources. Then, if thread B gets the lock Y and sleep () for a period of time, then when both threads wake up, they will wait for each other to release the lock resources and hold off, deadlock. Flag is used to obtain different locks for A and B.
Public class TestDeadLock {public void run () {MyThread mt = new MyThread (); new Thread (mt, "James "). start (); new Thread (mt, "Li Si "). start ();} class MyThread implements Runnable {private Object o1 = new Object (); private Object o2 = new Object (); private boolean flag = true; @ Overridepublic void run () {if (flag) {flag = false; synchronized (o1) {System. out. println (Thread. currentThread (). getName () + "have o1"); try {Thread. sleep (100);} catch (InterruptedException e) {e. printStackTrace ();} synchronized (o2) {System. out. println (Thread. currentThread (). getName () + "have o2") ;}} else {flag = true; synchronized (o2) {System. out. println (Thread. currentThread (). getName () + "have o2"); try {Thread. sleep (100);} catch (InterruptedException e) {e. printStackTrace ();} synchronized (o1) {System. out. println (Thread. currentThread (). getName () + "have o1") ;}}} public static void main (String [] args) {new TestDeadLock (). run ();}}