一段模拟死锁并中断死锁线程的demo

Demo

public class DeadLock implements Runnable{
    public static ReentrantLock lock1 = new ReentrantLock();
    public static ReentrantLock lock2 = new ReentrantLock();
    public int flag;
    public DeadLock(int flag) {
        this.flag = flag;
    }
    @Override
    public void run() {
        if (flag == 1) {
            try {
                lock1.lockInterruptibly();
                Thread.sleep(2000);
                lock2.lockInterruptibly();
            } catch (InterruptedException e) {
                System.out.println("flag=1被中断了");
            } finally {
                if (lock1.isHeldByCurrentThread()) {
                    lock1.unlock();
                }
                if (lock2.isHeldByCurrentThread()) {
                    lock2.unlock();
                }
            }
        }
        if (flag == 2) {
            try {
                lock2.lockInterruptibly();
                Thread.sleep(2000);
                lock1.lockInterruptibly();
            } catch (InterruptedException e) {
                System.out.println("flag=2被中断了");
            } finally {
                if (lock1.isHeldByCurrentThread()) {
                    lock1.unlock();
                }
                if (lock2.isHeldByCurrentThread()) {
                    lock2.unlock();
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(new DeadLock(1));
        Thread thread2 = new Thread(new DeadLock(2));
        thread1.start();
        thread2.start();
        Thread.sleep(5000);
        ThreadMXBean mxBean = ManagementFactory.getThreadMXBean();
        long[] deadlockedThreads = mxBean.findDeadlockedThreads();
        if (deadlockedThreads != null) {
            for (Thread thread : Thread.getAllStackTraces().keySet()) {
                for (long deadThreadId : deadlockedThreads) {
                    if (deadThreadId == thread.getId()) {
                        thread.interrupt();
                    }
                }
            }
        }
    }
}
一段模拟死锁并中断死锁线程的demo_第1张图片
肥肥小浣熊

你可能感兴趣的:(一段模拟死锁并中断死锁线程的demo)