jstack使用

jstack使用

jstack简介

jstack能得到运行java程序的java stack 和native stack的信息,可以轻松得知当前线程的运行情况

用法

  • jstack [ option ] pid
  • jstack [ option ] executable core
  • jstack [ option ] [server-id@]remote-hostname-or-IP
    一般使用 jstack pid 比较多

在dump中的几种主要状态

  • RUNNABLE,线程处于执行中
  • BLOCKED,线程被阻塞
  • WAITING,线程正在等待

例子讲解

1.下面是一个死锁代码

public class DeadLockSample extends Thread{
    private String first;
    private String second;

    public DeadLockSample(String name, String first, String second) {
        super(name);
        this.first = first;
        this.second = second;
    }

    @Override
    public void run() {
        synchronized (first) {
            System.out.println(this.getName() + " obtained:" + first);
            try {
                Thread.sleep(1000L);
                synchronized (second) {
                    System.out.println(this.getName() + " obtained:" + second);
                }
            } catch (InterruptedException e) {
                // Do nothing
            }
        }
    }

    public static void main(String[] args) throws InterruptedException{
        String lockA = "lockA";
        String lockB = "lockB";
        DeadLockSample t1 = new DeadLockSample("Thread1", lockA, lockB);
        DeadLockSample t2 = new DeadLockSample("Thread2", lockB, lockA);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
    }
}

2.在命令行输入:jps -m -l,找到进程ID
enter description here
继续输入:jstack 9076,thread dump信息如下:
enter description here
enter description here
结合代码分析线程栈信息,上面的输出非常明显,找到处于BLOCKED状态的线程,“Thread2"试图获取锁ID(见图中红色框),发现”Thread1"已经获取红色框中的锁,同理,绿颜色的也一样,jstack本身也会把类似的简单死锁抽取出来,直接打印出来,查看第二张图片。

posted @ 2018-07-05 21:24  慕橙-abby  阅读(212)  评论(0编辑  收藏  举报