多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
#### Jstack命令 jstack是java虚拟机自带的一种堆栈跟踪工具。用于打印出给定的java进程ID或core file或远程调试服务的java堆栈信息。 可以用来生成java虚拟机当前时刻的线程快照。 生成快照的主要目的是定位线程出现长时间停顿的原因,如*死锁、死循环、请求外部资源超时等待*等。 线程出现停顿的时候通过jstack来查看哥哥线程的调用堆栈,就可以直到没有响应的线程到底在后台做什么事情,或者等待什么资源。 ***** 例子: **示例代码** ``` public class DeadLock implements Runnable { private int flag; private static final Object a = new Object(); private static final Object b = new Object(); public DeadLock(int flag) { this.flag = flag; } @Override public void run() { if (flag == 1) { synchronized (a) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("当前线程:"+Thread.currentThread().getName()+"尝试获取b"); synchronized (b) { System.out.println("当前线程:"+Thread.currentThread().getName()+"获得了b"); } } } else { synchronized (b) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("当前线程:"+Thread.currentThread().getName()+"尝试获取a"); synchronized (a) { System.out.println("当前线程:"+Thread.currentThread().getName()+"等待获得a"); } } } } } ``` ***** ``` public class DeadLockLauncher { public static void main(String[] args) { final DeadLock deadLock1 = new DeadLock(1); final DeadLock deadLock2 = new DeadLock(0); Thread t1 = new Thread(deadLock1, "线程1"); Thread t2 = new Thread(deadLock2, "线程2"); t1.start(); t2.start(); } } ``` ***** * 打开命令行窗口,输入 jps ``` C:\Users\heyfan.xie>jps 16592 Jps 17232 DeadLockLauncher 7872 17092 Launcher 14040 Launcher ``` * 死锁启动类ID为 17232, 输入 jstack -F 17232 ``` C:\Users\heyfan.xie>jstack -F 17232 Attaching to process ID 17232, please wait... Debugger attached successfully. Server compiler detected. JVM version is 25.92-b14 Deadlock Detection: Found one Java-level deadlock: ============================= "线程2": waiting to lock Monitor@0x000000001f1e0288 (Object@0x000000076ba3f420, a java/lang/Object), which is held by "线程1" "线程1": waiting to lock Monitor@0x000000001f1e1728 (Object@0x000000076ba3f430, a java/lang/Object), which is held by "线程2" Found a total of 1 deadlock. Thread 3: (state = BLOCKED) Thread 22: (state = BLOCKED) - cn.cici.frigate.logistics.dead.DeadLock.run() @bci=120, line=41 (Interpreted frame) - java.lang.Thread.run() @bci=11, line=745 (Interpreted frame) Thread 21: (state = BLOCKED) - cn.cici.frigate.logistics.dead.DeadLock.run() @bci=34, line=30 (Interpreted frame) - java.lang.Thread.run() @bci=11, line=745 (Interpreted frame) Thread 15: (state = IN_NATIVE) - java.net.SocketInputStream.socketRead0(java.io.FileDescriptor, byte[], int, int, int) @bci=0 (Interpreted frame) - java.net.SocketInputStream.socketRead(java.io.FileDescriptor, byte[], int, int, int) @bci=8, line=116 (Interpreted frame) // 省略更多的信息 ``` * 可以看到* Found a total of 1 deadlock* 竞争锁定的对象为 java/lang/Object