Java~使用JDK自带的工具来检测是否有死锁的现象

    科技2022-07-11  97

    文章目录

    多线程的死锁使用JDK检测死锁

    多线程的死锁

    Java线程死锁是一个经典的多线程问题, 因为不同的线程都在等待根本不可能被释放的锁, 从而导致线程中的任务无法完成下面演示互相等待对方锁释放的死锁 /** * Created with IntelliJ IDEA. * Description: If you don't work hard, you will a loser. * User: Listen-Y. * Date: 2020-10-03 * Time: 20:37 */ public class DealThread implements Runnable { private String userName; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } //俩把锁 private final Object lock1 = new Object(); private final Object lock2 = new Object(); @Override public void run() { if ("a".equals(userName)) { synchronized (lock1) { System.out.println("userName=" + userName + " :" + "进入lock1"); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (lock2) { System.out.println("由lock1->进入->lock2"); } } } if ("b".equals(userName)) { synchronized (lock2) { System.out.println("userName=" + userName + " :" + "进入lock2"); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (lock1) { System.out.println("由lock2->进入->lock1"); } } } } } 启动类 /** * Created with IntelliJ IDEA. * Description: If you don't work hard, you will a loser. * User: Listen-Y. * Date: 2020-10-03 * Time: 20:42 */ public class Run { public static void main(String[] args) throws InterruptedException { DealThread dealThread = new DealThread(); dealThread.setUserName("a"); Thread thread = new Thread(dealThread); thread.start(); //注意这里是等待0.1秒 而线程是等待三秒 Thread.sleep(100); dealThread.setUserName("b"); Thread thread1 = new Thread(dealThread); thread1.start(); } } 运行结果 此时我们发现已经进入死锁

    使用JDK检测死锁

    在你安装JDK的bin目录下按住shift加鼠标右键启动powershell输入jps命令 知道我们启动类中死锁的线程的线程id是14784使用jstack命令 在最后面获得信息 浏览信息知道出现死锁的代码行在哪, 和在等待什么锁导致的死锁都可以发现.
    Processed: 0.009, SQL: 8