public class Deadlock {
private static Object obj1 = new Object();
private static Object obj2 = new Object();
public static void main(String[] args) {
new Thread(() -> {
System.out.println("线程1执行");
synchronized (obj1) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (obj2) {
}
}
}, "t1").start();
new Thread(() -> {
System.out.println("线程2执行");
synchronized (obj2) {
synchronized (obj1) {
}
}
}, "t2").start();
System.out.println("执行完毕");
}
}
通过thread命令定位
1,直接使用”thread“命令,输出线程统计信息。其中:BLOCKED 表示目前阻塞的线程数。
[arthas@11596]$ thread Threads Total: 26, NEW: 0, RUNNABLE: 8, BLOCKED: 2, WAITING: 4, TIMED_WAITING: 2, TERMINATED: 0, Internal threads: 10 ID NAME GROUP PRIORITY STATE %CPU DELTA_TIM TIME INTERRUPT DAEMON 2 Reference Handler system 10 WAITING 0.0 0.000 0:0.000 false true 3 Finalizer system 8 WAITING 0.0 0.000 0:0.000 false true 4 Signal Dispatcher system 9 RUNNABLE 0.0 0.000 0:0.000 false true 5 Attach Listener system 5 RUNNABLE 0.0 0.000 0:0.031 false true 14 arthas-timer system 5 WAITING 0.0 0.000 0:0.015 false true 17 arthas-NettyHttpTelnetBootstr system 5 RUNNABLE 0.0 0.000 0:0.015 false true 18 arthas-NettyWebsocketTtyBoots system 5 RUNNABLE 0.0 0.000 0:0.015 false true 19 arthas-NettyWebsocketTtyBoots system 5 RUNNABLE 0.0 0.000 0:0.015 false true 20 arthas-shell-server system 5 TIMED_WA 0.0 0.000 0:0.000 false true 21 arthas-session-manager system 5 TIMED_WA 0.0 0.000 0:0.000 false true 22 arthas-UserStat system 5 WAITING 0.0 0.000 0:0.000 false true 24 arthas-NettyHttpTelnetBootstr system 5 RUNNABLE 0.0 0.000 0:0.109 false true 25 arthas-command-execute system 5 RUNNABLE 0.0 0.000 0:0.015 false true 10 t1 main 5 BLOCKED 0.0 0.000 0:0.000 false false 11 t2 main 5 BLOCKED 0.0 0.000 0:0.000 false false 12 DestroyJavaVM main 5 RUNNABLE 0.0 0.000 0:0.156 false false2,执行“thread -b”命令,找出当前阻塞其他线程的线程,即造成死锁的罪魁祸首
[arthas@11596]$ thread -b
"t1" Id=10 BLOCKED on java.lang.Object@26dee7d7 owned by "t2" Id=11
at test.Deadlock.lambda$main$0(Deadlock.java:24)
- blocked on java.lang.Object@26dee7d7
- locked java.lang.Object@13a631ce <---- but blocks 1 other threads!
at test.Deadlock$$Lambda$1/250421012.run(Unknown Source)
at java.lang.Thread.run(Thread.java:748)
注:上面这个命令直接输出了 造成死锁的线程ID,和具体的代码位置,以及当前线程一共阻塞的线程数量:“<—- but blocks 1 other threads!“。
3,其他线程命令:thread –all, 显示所有的线程; thread id, 显示指定线程的运行堆栈; thread –state:查看指定状态的线程,如:thread –state BLOCKED; thread -n 3:展示当前最忙的前N个线程并打印堆栈;



