日期:2014-05-16 浏览次数:20501 次
/** * 死锁例子 * @author crane.ding * @since 2011-3-20 */ public class DeadLock { public static void main(String[] args) { final Object obj_1 = new Object(), obj_2 = new Object(); Thread t1 = new Thread("t1"){ @Override public void run() { synchronized (obj_1) { try { Thread.sleep(3000); } catch (InterruptedException e) {} synchronized (obj_2) { System.out.println("thread t1 done."); } } } }; Thread t2 = new Thread("t2"){ @Override public void run() { synchronized (obj_2) { try { Thread.sleep(3000); } catch (InterruptedException e) {} synchronized (obj_1) { System.out.println("thread t2 done."); } } } }; t1.start(); t2.start(); } }
$ java -cp deadlock.jar DeadLock & $
$ jps 3076 Jps 448 DeadLock $ jstack -l 448 > deadlock.jstack
2011-03-20 23:05:20 Full thread dump Java HotSpot(TM) Client VM (19.1-b02 mixed mode, sharing): "DestroyJavaVM" prio=6 tid=0x00316800 nid=0x9fc waiting on condition [0x00000000] java.lang.Thread.State: RUNNABLE Locked ownable synchronizers: - None "t2" prio=6 tid=0x02bcf000 nid=0xc70 waiting for monitor entry [0x02f6f000] java.lang.Thread.State: BLOCKED (on object monitor) at com.demo.DeadLock$2.run(DeadLock.java:40) - waiting to lock <0x22a297a8> (a java.lang.Object) - locked <0x22a297b0> (a java.lang.Object) Locked ownable synchronizers: - None "t1" prio=6 tid=0x02bce400 nid=0xba0 waiting for monitor entry [0x02f1f000] java.lang.Thread.State: BLOCKED (on object monitor) at com.demo.DeadLock$1.run(DeadLock.java:25) - waiting to lock <0x22a297b0> (a java.lang.Object) - locked <0x22a297a8> (a java.lang.Object) Locked ownable synchronizers: - None "Low Memory Detector" daemon prio=6 tid=0x02bb9400 nid=0xa6c runnable [0x00000000] java.lang.Thread.State: RUNNABLE Locked ownable synchronizers: - None "CompilerThread0" daemon prio=10 tid=0x02bb2800 nid=0xcb8 waiting on condition [0x00000000] java.lang.Thread.State: RUNNABLE Locked ownable synchronizers: - None "Attach Listener" daemon prio=10 tid=0x02bb1000 nid=0x7f4 waiting on condition [0x00000000] java.lang.Thread.State: RUNNABLE Locked ownable synchronizers: - None "Signal Dispatcher" daemon prio=10 tid=0x02bd2800 nid=0xd80 runnable [0x00000000] java.lang.Thread.State: RUNNABLE Locked ownable synchronizers: - None "Finalizer" daemon prio=8 tid=0x02bab000 nid=0xe1c in Object.wait() [0x02d3f000] java.lang.Thread.State: WAITING (on object monitor) at java.lang.Object.wait(Native Method) - waiting on <0x229e1148> (a java.lang.ref.ReferenceQueue$Lock) at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:118) - locked <0x229e1148> (a java.lang.ref.ReferenceQueue$Lock) at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:134) at java.lang.ref.Finalizer$FinalizerThread.run(Finalize