JavaRush /Java Blog /Random-TW /如何從線程組中獲取死線程列表?28級
Dead_MOPO3
等級 36
Москва

如何從線程組中獲取死線程列表?28級

在 Random-TW 群組發布
嗯,實際上,問題本身就在標題中。誰想出來了,告訴我。我找到了這個選項,但我根本不喜歡它,而且它不起作用) public static void main(String[] args) { /* * For testing purposes */ ThreadGroup tg = new ThreadGroup( "MyThreadGroup" ); Thread subThread = new Thread( tg, "New Thread - Inactive" ); try { /* * GETTING THREADS - PROBABLY BETTER TO GET IT BY USING * getDeclaredFields() AND LOOPING TILL GET ONE OF TYPE * Thread[] SINCE A FUTURE VERSION MIGHT CHANGE THE NAME * BUT SINCE IS PACKAGE-LEVEL ACCESS, IT'S PROBABLY USED * ELSEWHERE IN THE PACKAGE, AND THIS IS JUST AN EXAMPLE */ Field field = tg.getClass().getDeclaredField( "threads" ); //NEED TO SUPPRESS ACCESS CHECKS field.setAccessible( true ); //EVEN IF SECURITY IS OFF YOU NEED THIS!!!! Thread[] tgThreads = ( Thread[] ) field.get( tg ); for ( int i = 0; i < tgThreads.length; i++ ) { if ( tgThreads[ i ] != null ) System.out.println( tgThreads[ i ].getName() + " = " + tgThreads[ i ].isAlive() ); } } catch (NoSuchFieldException nsfe) { nsfe.printStackTrace(); } catch (IllegalAccessException iae) { iae.printStackTrace(); } } 事實證明,該行Thread[] tgThreads = ( Thread[] ) field.get( tg ); 並沒有為我生成數組。我讀到,您似乎可以以某種方式進入 System.SecurityManager 並設定 ReflectPermission("suppressAccessChecks")。但該方法過於硬編碼。透過反射進入私有領域...
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION