多线程【死锁案例及死锁的排查】

一、死锁案例

class HoldLockThread extends Thread{

    private String lockA;
    private String lockB;

    public HoldLockThread(String lockA, String lockB){
        this.lockA = lockA;
        this.lockB = lockB;
    }

    @Override
    public void run() {
        synchronized (lockA){
            System.out.println(Thread.currentThread().getName() + "持有:" + lockA + "锁");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (lockB){
                System.out.println(Thread.currentThread().getName() + "持有:" + lockA + "锁");
            }
        }
    }
}

public class DeadLockDemo {
    public static void main(String[] args) {
        String lockA = "lockA";
        String lockB = "lockB";

        new Thread(new HoldLockThread(lockA, lockB), "线程1").start();
        new Thread(new HoldLockThread(lockB, lockA), "线程2").start();
    }
}

二、问题的排查

当程序运行到一半卡不不继续运行时,如何排查是不是死锁导致的呢?

主要通过两个命令来排查,分别为:jps 和 jstack。

(一)jps

可以在 IDEA 的 Terminal 工具输入:jps -l 命令来查看当前发生死锁的线程id

(二)jstack

针对获取到的线程 id,使用 jstack 命令查看栈相关信息。

如果出现如下信息,则说明确实是程序中出现死锁了,那么只需做相关调整即可解决。

Found one Java-level deadlock:
=============================
"线程2":
waiting to lock monitor 0x000002937e722398 (object 0x00000000d613fa60, a java.lang.String),
which is held by "线程1"
"线程1":
waiting to lock monitor 0x000002937d8ef548 (object 0x00000000d613fa98, a java.lang.String),
which is held by "线程2"

Java stack information for the threads listed above:
===================================================
"线程2":
     at com.zuobiao.thread.HoldLockThread.run(DeadLockDemo.java:23)
        - waiting to lock <0x00000000d613fa60> (a java.lang.String)
        - locked <0x00000000d613fa98> (a java.lang.String)
        at java.lang.Thread.run(Thread.java:748)
"线程1":
        at com.zuobiao.thread.HoldLockThread.run(DeadLockDemo.java:23)
        - waiting to lock <0x00000000d613fa98> (a java.lang.String)
        - locked <0x00000000d613fa60> (a java.lang.String)
        at java.lang.Thread.run(Thread.java:748)

Found 1 deadlock.java

Java新手,若有错误,欢迎指正!

posted @ 2021-02-20 20:49  跑调大叔!  阅读(296)  评论(0编辑  收藏  举报