使用ThreadMXBean发现死锁

利用JDK自带的ThreadMXBean发现程序中出现的死锁。

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.concurrent.TimeUnit;

public class FindDeadLock implements Runnable {

    int flag = 0;
    Object lock1 = new Object();
    Object lock2 = new Object();

    public static void main(String[] args) throws InterruptedException {
        FindDeadLock deadLock1 = new FindDeadLock();
        FindDeadLock deadLock2 = new FindDeadLock();
        deadLock1.flag = 1;
        deadLock2.flag = 2;
        new Thread(deadLock1).start();
        new Thread(deadLock2).start();
        TimeUnit.SECONDS.sleep(2);
        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        long[] deadlockedThreads = threadMXBean.findDeadlockedThreads();
        if (deadlockedThreads != null && deadlockedThreads.length > 0) {
            for (int i = 0; i < deadlockedThreads.length; i++) {
                ThreadInfo threadInfo = threadMXBean.getThreadInfo(deadlockedThreads[i]);
                System.out.println("可找到你了,不能让你跑了!" + threadInfo.getThreadName());
            }
        }
    }


    @Override
    public void run() {
        if (flag == 1) {
            synchronized (lock1) {
                System.out.println("lock1获取到锁1");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock2) {
                    System.out.println("lock1获取到锁2");
                }
            }
        } else if (flag == 2) {
            synchronized (lock2) {
                System.out.println("lock2获取到锁2");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock1) {
                    System.out.println("lock2获取到锁1");
                }
            }
        }

    }
}

 

展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 数字20 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读