从线程对象的 ID 获取对线程对象的引用
2022-09-01 19:29:49
如果我知道与正在运行的线程关联的 ID,如何获取对该线程的引用?
例如:
long threadID = 12342;
Thread thread = (What goes here?) getThreadFromId(threadID); //I know this is totally made up
如果我知道与正在运行的线程关联的 ID,如何获取对该线程的引用?
例如:
long threadID = 12342;
Thread thread = (What goes here?) getThreadFromId(threadID); //I know this is totally made up
你有两种方法可以做到这一点。两者都很简单:
旧方法:获取您可能访问的根线程组。getParent() in loop.并致电Thread.currentThread().getGroup()
enumerate(Thread[])
较新(虽然较慢)。for (Thread t : Thread.getAllStackTraces().keySet()) if (t.getId()==id)...
第一种方法有一个小问题,由于 中的 bug,ThreadGroup 可能根本不枚举任何内容。ThreadGroup.destroy()
不过,第二个速度较慢,并且存在安全漏洞。
您可以使用以下代码来获取线程名称(例如,我想获取处于死锁状态的线程的名称)
ThreadMXBean threadMB = ManagementFactory.getThreadMXBean();
long threadIds[] = threadMB.findDeadlockedThreads();
for (long id : threadIds) {
System.out.println("The deadLock Thread id is : " + id
+ " > "
+
threadMB.getThreadInfo(id).getThreadName());
}