Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by NavBot

...

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
bgColor#FFcccc
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 &lt;< 500000; i++) { } // Delay to demonstrate TOCTOU condition
		
    System.out.println(&quot;"Active Threads in Thread Group at point (2):&quot;" +
      t.getThreadGroup().getName() + &quot; &quot;" " + Thread.activeCount());
		
    int n = Thread.enumerate(ta);
    System.out.println(&quot;"Enumerating...&quot;");
    for(int i = 0; i &lt;< n; i++) {
      System.out.println(&quot;"Thread &quot;" + i + &quot;" = &quot;" + ta[i].getName());
    } 
  }
} 

class HandleRequest implements Runnable {
  public void run() {
    System.out.println(&quot;"Active Threads in Thread Group (Handler thread invoked this): &quot;" + 
    Thread.currentThread().getThreadGroup().getName() + &quot; &quot;" " + Thread.activeCount());		
  }
}

...

CON00-J. Do not invoke a superclass method or constructor from a synchronized region in the subclass&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;      11. Concurrency (CON)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;      CON02-J. Facilitate thread reuse by using Thread Pools