JavaRush /จาวาบล็อก /Random-TH /จะรับรายการเธรดที่ไม่ทำงานจาก ThreadGroup ได้อย่างไร ระดั...
Dead_MOPO3
ระดับ
Москва

จะรับรายการเธรดที่ไม่ทำงานจาก ThreadGroup ได้อย่างไร ระดับ 28

เผยแพร่ในกลุ่ม
ที่จริงแล้วคำถามนั้นอยู่ในชื่อเรื่อง ใครคิดออกบอกหน่อย ฉันพบตัวเลือกนี้ แต่ฉันไม่ชอบเลยและมันใช้งานไม่ได้) 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