一个命令查看死锁位置

代码
package com.example.provider.lock;

import lombok.SneakyThrows;

import java.util.concurrent.TimeUnit;

public class DeadLock {

    private static String a = "a";
    private static String b = "b";

    public static void main(String[] args) throws InterruptedException {
        new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                synchronized (a){
                    System.out.println(Thread.currentThread().getName()+" lock a");
                    Thread.sleep(3000);
                    synchronized (b){
                        System.out.println(Thread.currentThread().getName()+" lock b");
                    }
                }
            }
        }).start();
        new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                synchronized (b){
                    System.out.println(Thread.currentThread().getName()+" lock b");
                    Thread.sleep(3000);
                    synchronized (a){
                        System.out.println(Thread.currentThread().getName()+" lock a");
                    }
                }
            }
        }).start();
        TimeUnit.HOURS.sleep(1);
    }


}

查看死锁

jstack -l <pid>

结果:

Found one Java-level deadlock:
=============================
"Thread-1":
  waiting to lock monitor 0x0000022b10807308 (object 0x0000000716dc66e8, a java.lang.String),
  which is held by "Thread-0"
"Thread-0":
  waiting to lock monitor 0x0000022b10807258 (object 0x0000000716dc6718, a java.lang.String),
  which is held by "Thread-1"

Java stack information for the threads listed above:
===================================================
"Thread-1":
        at com.example.provider.lock.DeadLock$2.run(DeadLock.java:38)
        - waiting to lock <0x0000000716dc66e8> (a java.lang.String)
        - locked <0x0000000716dc6718> (a java.lang.String)
        at java.lang.Thread.run(Thread.java:748)
"Thread-0":
        at com.example.provider.lock.DeadLock$1.run(DeadLock.java:25)
        - waiting to lock <0x0000000716dc6718> (a java.lang.String)
        - locked <0x0000000716dc66e8> (a java.lang.String)
        at java.lang.Thread.run(Thread.java:748)

Found 1 deadlock.

可以发现,死锁发生 在DeadLock 的 run 方法

更多推荐