package thread;

public class RaceThread extends Thread {

  public void run() {
    while (true) {
      printThreadGroups();
      try {
        Thread.sleep(10000);
      } catch (InterruptedException e) {
      }

    }
  }


  public ThreadGroup getSystemThreadGroup() {

    ThreadGroup systemThreadGroup;
    ThreadGroup parentThreadGroup;

    systemThreadGroup = Thread.currentThread().getThreadGroup();

    while ((parentThreadGroup = systemThreadGroup.getParent()) != null)
      systemThreadGroup = parentThreadGroup;

    return systemThreadGroup;
  }


  public ThreadGroup[] getThreadGroupsArray() {

    ThreadGroup systemThreadGroup = getSystemThreadGroup();

    int numberOfGroups = systemThreadGroup.activeGroupCount() + 1;

    ThreadGroup threadGroupsArray[] = new
        ThreadGroup[numberOfGroups];

    systemThreadGroup.enumerate(threadGroupsArray);

    threadGroupsArray[numberOfGroups] = systemThreadGroup;

    return threadGroupsArray;
  }

  public Thread[] getThreadsArray() {

    ThreadGroup systemThreadGroup = getSystemThreadGroup();

    Thread threadsArray[] = new Thread[systemThreadGroup.activeCount()];
    systemThreadGroup.enumerate(threadsArray);

    return threadsArray;
  }

  public void printThreadGroups() {
    getSystemThreadGroup().list();
  }

  public void printThreads() {
    Thread[] threadsArray = getThreadsArray();
    for (int i = 0; i < threadsArray.length; i++)
      System.out.println(threadsArray[i]);
  }

  public void printThreadsAndGroups() {
    System.out.println("The threads are:");
    printThreads();
    System.out.println("The groups are:");
    printThreadGroups();
  }

}