首先,编写一个死锁程序
1 package deadlock;
2
3 public class testJstack {
4 final static Object resource_1 = new Object();
5 final static Object resource_2 = new Object();
6
7 public static void main(String[] args) {
8 Thread t1 = new Thread("t1") {
9 public void run() {
10 synchronized (resource_1) {
11 try {
12 Thread.sleep(3000);
13 } catch (InterruptedException e) {
14 }
15 System.out.println("locked resource_1");
16 synchronized (resource_2) {
17 System.out.println("thread t1 done.");
18 }
19 }
20 }
21 };
22
23 Thread t2 = new Thread("t2") {
24 public void run() {
25 synchronized (resource_2) {
26 System.out.println("locked resource_2");
27 synchronized (resource_1) {
28 System.out.println("thread t2 done.");
29 }
30 }
31 }
32 };
33 t1.start();
34 t2.start();
35 }
36 }
程序运行结果是:
lock resource_2
lock resource_1
接下来在终端中输入jsp查看当前运行的java程序:
7480 testJstack
13420 Jps
获取testJstack的进程ID为7480.然后使用命令:
jstack -l 7480 >deadlock.jstack
将jstack检测结果放入文件deadlock.jstack。使用vim查看该文件:
java.lang.Thread.State: RUNNABLE
Locked ownable synchronizers:
- None
java.lang.Thread.State: RUNNABLE
java.lang.Thread.State: BLOCKED (on object monitor)
at testJstack$2.run(testJstack.java:29)
- waiting to lock <0x8c087670> (a java.lang.Object)
- locked <0x8c087678> (a java.lang.Object)
java.lang.Thread.State: BLOCKED (on object monitor)
at testJstack$1.run(testJstack.java:15)
Locked ownable synchronizers:
- None
java.lang.Thread.State: RUNNABLE
Locked ownable synchronizers:
- None
java.lang.Thread.State: RUNNABLE
Locked ownable synchronizers:
java.lang.Thread.State: RUNNABLE
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- locked <0x8c050b30> (a java.lang.ref.ReferenceQueue$Lock)
Locked ownable synchronizers:
- None
- waiting on <0x8c050a30> (a java.lang.ref.Reference$Lock)
at java.lang.Object.wait(Object.java:485)
- locked <0x8c050a30> (a java.lang.ref.Reference$Lock)
Locked ownable synchronizers:
"VM Thread" prio=10 tid=0x0807e800 nid=0x260c runnable
JNI global references: 576
Found one Java-level deadlock:
=============================
"t2":
which is held by "t1"
"t1":
which is held by "t2"
Java stack information for the threads listed above:
===================================================
"t2":
at testJstack$2.run(testJstack.java:29)
- waiting to lock <0x8c087670> (a java.lang.Object)
- locked <0x8c087678> (a java.lang.Object)
"t1":
at testJstack$1.run(testJstack.java:15)
- waiting to lock <0x8c087678> (a java.lang.Object)
- locked <0x8c087670> (a java.lang.Object)
Found 1 deadlock.