1 class Demo3 2 { 3 public static void main(String[] args) 4 { 5 System.out.println("Hello World!"); 6 T1 t1 = new T1(); 7 T2 t2 = new T2(); 8 new Thread(t1).start(); 9 new Thread(t2).start(); 10 } 11 } 12 class MyLock 13 { 14 static Object obj1 = new Object(); 15 static Object obj2 = new Object(); 16 } 17 class T1 implements Runnable 18 { 19 public void run(){ 20 while(true){ 21 synchronized(MyLock.obj1){ 22 System.out.println("t1 obj1"); 23 synchronized(MyLock.obj2){ 24 System.out.println("t1 obj2"); 25 } 26 } 27 } 28 } 29 } 30 class T2 implements Runnable 31 { 32 public void run(){ 33 while(true){ 34 synchronized(MyLock.obj2){ 35 System.out.println("t2 obj2"); 36 synchronized(MyLock.obj1){ 37 System.out.println("t2 obj1"); 38 } 39 } 40 } 41 } 42 }
造成死锁的原因,同步的嵌套,当持有obj1锁想要拿到obj2锁的时候,恰好另一个类持有obj2锁,想要拿到obj1锁。因为彼此没有完成任务都不释放已拿到的锁,同时又需要对方的锁,所以造成锁死!
原文:http://www.cnblogs.com/linson0116/p/3581944.html