有没有办法获取死锁线程的引用,然后令它马上停止呢?
来源:14-10 ThreadMXBean工具介绍

Small_6
2019-12-28
// The management interface for the thread system of the JVM // JVM has a single instance of the implementation class of this interface. ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); // array of IDs of the threads that are deadlocked waiting for object monitors or ownable synchronizers // TODO 有没有办法获取死锁线程的引用?这样就可以直接interrupt()发起中断期望^_^,我看了一下API貌似没有这种方法。 // 当然,这样我们的代码就像“超级管理员”一样了。(这样有可能把两个死锁线程都杀死,而不是杀掉一个线程。) long[] deadlockedThreads = threadMXBean.findDeadlockedThreads(); if (deadlockedThreads != null && deadlockedThreads.length > 0) { for (int i = 0; i < deadlockedThreads.length; i++) { ThreadInfo threadInfo = threadMXBean.getThreadInfo(deadlockedThreads[i]); String threadName = threadInfo.getThreadName(); System.out.println("发现死锁,线程的名字是:" + threadName); } }
写回答
1回答
-
可以的,
在ThreadInfo中,拥有线程ID,因此可以使用它来获取对线程的引用。
ThreadInfo[] threadInfos = ....;
Set<Long> tIds = new HashSet<>();
for (ThreadInfo tIndo : threadInfos) {
tIds.add(tIndo.getId());
}
for (Thread t : Thread.getAllStackTraces().keySet()) {
if(tIds.contains(t.getId()) {
t.interrupt();
}
}参考:https://www.thinbug.com/q/33233325
142019-12-28
相似问题
使用线程池是否可以天然避免死锁
回答 1
死锁发生条件
回答 1