Właściwie samo pytanie jest w tytule. Kto to wymyślił, powiedz mi. Znalazłem taką opcję, ale zupełnie mi się nie podoba i nie działa)
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(); } }
Okazuje się, że linia Thread[] tgThreads = ( Thread[] ) field.get( tg );
nie generuje mi tablicy. Czytałem, że wygląda na to, że możesz w jakiś sposób przejść do System.SecurityManager i ustawić ReflectPermission("suppressAccessChecks"). ale podejście jest zbyt zakodowane. wejść na prywatne pola poprzez refleksję...
GO TO FULL VERSION