...
Wiki Markup |
---|
A programmer may sometimes wish to enumerate all the threads in a group as a precursor to other operations. This is accomplished by using the {{activeCount()}} method that ""Returns an estimate of the number of active threads in this thread group. "" \[[API 06|AA. Java References#API 06]\]. Notice that there is no absolute word on whether it returns the exact count or not; the definition of _active_ also has a different connotation here. A thread that is constructed and not started is still counted by the {{activeCount()}} method as _active_. |
...
Code Block | ||
---|---|---|
| ||
class NetworkHandler implements Runnable { private static ThreadGroup tg = new ThreadGroup("Chief""Chief"); public void run() { try { method1(); method2(); Thread.sleep(500); } catch(InterruptedException e) { // Forward to handler } } public static void method1() throws InterruptedException { Thread t1 = new Thread(tg, new HandleRequest(), "t1""t1"); Thread t2 = new Thread(tg, new HandleRequest(), "t2""t2"); t1.start(); t2.start(); } public static void method2() { Thread t3 = new Thread(tg, new HandleRequest(), "t3""t3"); Thread t4 = new Thread(tg, new HandleRequest(), "t4""t4"); t3.start(); t4.start(); } public static void main(String[] args) throws InterruptedException { Thread t = new Thread(tg, new NetworkHandler(), "t""t"); t.start(); System.out.println(""Active Threads in Thread Group at point (1):"" + t.getThreadGroup().getName() + " "" " + Thread.activeCount()); Thread ta[] = new Thread[Thread.activeCount()]; for(int i = 0; i << 500000; i++) { } // Delay to demonstrate TOCTOU condition System.out.println(""Active Threads in Thread Group at point (2):"" + t.getThreadGroup().getName() + " "" " + Thread.activeCount()); int n = Thread.enumerate(ta); System.out.println(""Enumerating...""); for(int i = 0; i << n; i++) { System.out.println(""Thread "" + i + "" = "" + ta[i].getName()); } } } class HandleRequest implements Runnable { public void run() { System.out.println(""Active Threads in Thread Group (Handler thread invoked this): "" + Thread.currentThread().getThreadGroup().getName() + " "" " + Thread.activeCount()); } } |
...
CON00-J. Do not invoke a superclass method or constructor from a synchronized region in the subclass 11. Concurrency (CON) CON02-J. Facilitate thread reuse by using Thread Pools