如何查看Java进程发生了死锁?
运行一个Java程序, 发生了死锁, 如何查看?
运行以下程序发生死锁
public class DeadLockTest {
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
synchronized (B.class) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (A.class) {
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
synchronized (A.class) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (B.class) {
}
}
}
}).start();
}
}
class A {
}
class B {
}
查看死锁方法一:
打开%JAVA_HOME%/bin/jconsole.exe
,
![image-20210409122232936](https://img2020.cnblogs.com/blog/1853443/202104/1853443-20210409122938248-1369953475.png)
![image-20210409122313725](https://img2020.cnblogs.com/blog/1853443/202104/1853443-20210409122938011-1725818148.png)
看这两个线程互相锁住的和阻塞的资源, 就能判断发生了死锁。
查看死锁方法二:
使用jps
命令先查看进程号
![image-20210409122457224](https://img2020.cnblogs.com/blog/1853443/202104/1853443-20210409122937614-212014862.png)
然后运行jstack -l 2340
![image-20210409122623738](https://img2020.cnblogs.com/blog/1853443/202104/1853443-20210409122937074-269793945.png)
如图, 发生了死锁。