Listing 4: File ListThreads.java: Illustrates the Default Thread Group and Thread.join

class ListThreads
{
   public static void list(String label)
   {
      ThreadGroup group = Thread.currentThread().getThreadGroup();
      int nActive = group.activeCount();
      System.out.println("\n" + label + ":\n=====");
      System.out.println("nActive = " + nActive);
      Thread threads[] = new Thread[nActive];
      int nThreads = group.enumerate(threads);
      System.out.println("nThreads = " + nThreads);
      for (int i = 0; i < nThreads; ++i)
         System.out.println(threads[i]);
      System.out.println();
   }

   public static void main(String[] args)
   {
      Thread t1 = new MyThread("DessertTopping", 200, 10);
      Thread t2 = new MyThread("FloorWax", 300, 7);
      list("Before");
      t1.start();
      t2.start();
      list("During");

      try
      {
         // Wait for worker threads to finish:
         t1.join();
         t2.join();
      }
      catch (InterruptedException x)
      {
         // won't happen
      }
      list("After");
   }
}

/* Output:

Before:
=====
nActive = 3
nThreads = 1
Thread[main,5,main]


During:
=====
nActive = 3
nThreads = 3
Thread[main,5,main]
Thread[DessertTopping,5,main]
Thread[FloorWax,5,main]

DessertTopping
FloorWax
DessertTopping
FloorWax
DessertTopping
DessertTopping
FloorWax
DessertTopping
FloorWax
DessertTopping
DessertTopping
FloorWax
DessertTopping
FloorWax
DessertTopping
DessertTopping
FloorWax

After:
=====
nActive = 1
nThreads = 1
Thread[main,5,main]

*/
— End of Listing —