JVM基础篇-线程运行诊断

JVM基础篇-线程运行诊断

CPU占用过多定位

  • 用top定位哪个进程对cpu的占用过高
  • ps H -eo pid,tid,%cpu | grep 进程id (用ps命令进一步定位是哪个线程引起的cpu占用过高)
  • jstack 进程id 可以根据线程id 找到有问题的线程,进一步定位到问题代码的源码行号

程序运行很长时间没有结果

  • 使用jps查找java进程id
  • 使用jstack 进程id查看异常信息
示例
package com.vmware.stack;

class A {

}

class B {

}

public class Demo4 {
    static A a = new A();
    static B b = new B();

    public static void main(String[] args) throws InterruptedException {
        new Thread(() -> {
            synchronized (a) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (b) {
                    System.out.println("获取了a和b");
                }
            }
        }).start();
        Thread.sleep(1000);
        new Thread(() -> {
            synchronized (b) {
                synchronized (a) {
                    System.out.println("获得了a和b");
                }
            }
        }).start();
    }
}

jstack info

Found one Java-level deadlock:
=============================
"Thread-0":
  waiting to lock monitor 0x00007f90a8000ff0 (object 0x000000071a9cb480, a com.vmware.stack.B),
  which is held by "Thread-1"

"Thread-1":
  waiting to lock monitor 0x00007f909c000ff0 (object 0x000000071a9ca6a0, a com.vmware.stack.A),
  which is held by "Thread-0"

Java stack information for the threads listed above:
===================================================
"Thread-0":
	at com.vmware.stack.Demo4.lambda$main$0(Demo4.java:24)
	- waiting to lock <0x000000071a9cb480> (a com.vmware.stack.B)
	- locked <0x000000071a9ca6a0> (a com.vmware.stack.A)
	at com.vmware.stack.Demo4$$Lambda$14/0x0000000800c01618.run(Unknown Source)
	at java.lang.Thread.run([email protected]/Thread.java:833)
"Thread-1":
	at com.vmware.stack.Demo4.lambda$main$1(Demo4.java:32)
	- waiting to lock <0x000000071a9ca6a0> (a com.vmware.stack.A)
	- locked <0x000000071a9cb480> (a com.vmware.stack.B)
	at com.vmware.stack.Demo4$$Lambda$17/0x0000000800c01838.run(Unknown Source)
	at java.lang.Thread.run([email protected]/Thread.java:833)

Found 1 deadlock.

你可能感兴趣的:(JVM,jvm)