标签:
1 public class DeadLock3 implements Runnable { 2 3 private static Object obj1 = new Object(); 4 private static Object obj2 = new Object(); 5 6 @Override 7 public void run() { 8 System.out.println("Current Thread: " + Thread.currentThread().getName()); 9 for (int i = 1; i < 3; i++) { 10 System.out.println("i: " + i); 11 if (i % 2 != 0) { 12 //odd 13 System.out.println("Lock object1 first then lock object2"); 14 synchronized (obj1) { 15 try { 16 Thread.sleep(500); 17 } catch (InterruptedException e) { 18 e.printStackTrace(); 19 } 20 synchronized (obj2) {} 21 } 22 } else { 23 //even 24 System.out.println("Lock object2 first then lock object1"); 25 synchronized (obj2) { 26 try { 27 Thread.sleep(500); 28 } catch (InterruptedException e) { 29 e.printStackTrace(); 30 } 31 synchronized (obj1) {} 32 } 33 } 34 } 35 } 36 37 public static void main(String[] args) { 38 new Thread(new DeadLock3()).start(); 39 new Thread(new DeadLock3()).start(); 40 } 41 }
从运行结果可以看出,Thread-0和Thread-1都进入了run方法,Thread-0是先锁住object1再锁住object2, 而Thread-1则相反,当Thread-0成功锁住object1再试图去锁定object2的时候,发现object2已经被Thread-1锁住了,于是Thread-0只要等在那里,等待Thread-1释放object2的锁; 这个时候,Thread-1成功锁住了object2再试图去锁住object1的时候发现object1已经被锁住了,于是只好等在那里,等待Thread-0释放object1的锁,于是造成了相互等待的死锁现象。
利用java内置的工具jps可以查看当前JVM正在运行的Java线程
利用java内置的工具jstack可以查看某线程的情况,例如是否死锁
标签:
原文地址:http://www.cnblogs.com/stonefeng/p/5837514.html