JavaRush /Java 博客 /Random-ZH /如何从线程组中获取死线程列表?28级
Dead_MOPO3
第 36 级
Москва

如何从线程组中获取死线程列表?28级

已在 Random-ZH 群组中发布
嗯,实际上,问题本身就在标题中。谁想出来了,告诉我一下。我找到了这个选项,但我根本不喜欢它,而且它不起作用) 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