如果我知道與該線程關聯的ID,如何獲取正在運行的線程的引用?從ID獲取對線程對象的引用
例如
long threadID = 12342;
Thread thread = (What goes here?) getThreadFromId(threadID); //I know this is totally made up
如果我知道與該線程關聯的ID,如何獲取正在運行的線程的引用?從ID獲取對線程對象的引用
例如
long threadID = 12342;
Thread thread = (What goes here?) getThreadFromId(threadID); //I know this is totally made up
你有2種方式來做到這一點。 兩者都是相當簡單:
老辦法:讓您可以在循環訪問Thread.currentThread().getGroup()
..getParent()根線程組。並致電enumerate(Thread[])
更新(儘管較慢)。 for (Thread t : Thread.getAllStackTraces().keySet()) if (t.getId()==id)...
第一種方法有一個小問題,由於在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());
}