赞
踩
DeadlockChecker.java
static class DeadlockChecker { private final static ThreadMXBean mbean = ManagementFactory.getThreadMXBean(); public static void check() { Thread tt = new Thread(() -> { while(true) { long[] deadlockedThreadIds = mbean.getAllThreadIds(); if (deadlockedThreadIds != null) { ThreadInfo[] threadInfos = mbean.getThreadInfo(deadlockedThreadIds); for (Thread t : Thread.getAllStackTraces().keySet()) { for (int i = 0; i < threadInfos.length; i++) { if (t.getId() == threadInfos[i].getThreadId()) { System.out.println(t.getName()); t.interrupt(); } } } } try { Thread.sleep(5000); } catch (InterruptedException e) {} } }); tt.setDaemon(true); tt.start(); } }
举个栗子:
import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.util.concurrent.locks.ReentrantLock; /** * <p> @Title LockInterrupt * <p> @Description 锁中断测试 * * @author ACGkaka * @date 2020/12/8 14:46 */ public class LockInterrupt extends Thread { public static ReentrantLock lock1 = new ReentrantLock(); public static ReentrantLock lock2 = new ReentrantLock(); int lock; public LockInterrupt(int lock, String name) { super(name); this.lock = lock; } @Override public void run() { try { if (lock == 1) { lock1.lockInterruptibly(); try { Thread.sleep(500); } catch (Exception e) {} lock2.lockInterruptibly(); } else { lock2.lockInterruptibly(); try { Thread.sleep(500); } catch (Exception e) {} lock1.lockInterruptibly(); } } catch (Exception e) { } finally { if (lock1.isHeldByCurrentThread()) { lock1.unlock(); } if (lock2.isHeldByCurrentThread()) { lock2.unlock(); } System.out.println(Thread.currentThread().getId() + ":线程退出"); } } public static void main(String[] args) throws InterruptedException { LockInterrupt t1 = new LockInterrupt(1, "LockInterrupt1"); LockInterrupt t2 = new LockInterrupt(2, "LockInterrupt2"); t1.start(); t2.start(); Thread.sleep(1000); DeadlockChecker.check(); } static class DeadlockChecker { private final static ThreadMXBean mbean = ManagementFactory.getThreadMXBean(); public static void check() { Thread tt = new Thread(() -> { while(true) { long[] deadlockedThreadIds = mbean.getAllThreadIds(); if (deadlockedThreadIds != null) { ThreadInfo[] threadInfos = mbean.getThreadInfo(deadlockedThreadIds); for (Thread t : Thread.getAllStackTraces().keySet()) { for (int i = 0; i < threadInfos.length; i++) { if (t.getId() == threadInfos[i].getThreadId()) { System.out.println(t.getName()); t.interrupt(); } } } } try { Thread.sleep(5000); } catch (InterruptedException e) {} } }); tt.setDaemon(true); tt.start(); } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。