Author: Ching
Original address: http://blog.csdn.net/qingdujun/article/details/39367655
This article demonstrates, tread multi-threaded deadlock, simple analysis of the cause of the deadlock, and show a deadlock of the small demo.
1) Cause of deadlock
2) Small Demo
One, the cause of the deadlock: Synchronization in a nested synchronization.
Second Deadlock small demo: (lock Loacka need to lock lockb, lock lockb also need to lock locka, and then add while (true) in the inside a crazy turn, directly locked. )
Package NO.ZUO.NO.DIE;//1. Implement Runnable Interface class Zuosi implements Runnable{private Boolean flag; Zuosi (Boolean f) {flag = f;} 2. Override the Run method public void run () {if (flag) {while (true) {synchronized (Clock.locka) {System.out.println ("if Locka"); Synchronized (clock.lockb) {System.out.println ("if lockb");}}} else {while (true) {synchronized (clock.lockb) {System.out.println ("Else lockb"); synchronized (Clock.locka) { System.out.println ("Else Locka");}}}}} It contains 2 Locks class Clock{static Object Locka = new Object (); static object lockb = new Object ();} public class Cdeadlock {public static void main (string[] args) {//3. Create 2 threads thread T1 = new Thread (new Zuosi (true)); Thread t2 = new Thread (new Zuosi (false)),//4. Boot thread T1.start (); T2.start ();}}
Run the display result (Is it dead?) It's locked!!! ):
References: Java video Bi Xiangdong presenter
Original address: http://blog.csdn.net/qingdujun/article/details/39367655
Java Tread Multithreading (3) deadlock