使用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");
                }
            }
        }

    }
}

 

你可能感兴趣的:(并发,死锁,java)