title: How to Obtain Thread Info/Statistics in Java
body: <p>Title says it all.  I have some code which is included below and I am wondering how I would go about obtaining the statistics/information related to the threads (i.e. how many different threads are running, names of the different threads).  For consistency sake, image the code is run using <code>22 33 44 55</code> as command line arguments.</p>
  
  <p>I am also wondering what the purpose of the try blocks are in this particular example.  I understand what try blocks do in general, but specifically what do the try blocks do for the threads.</p>
  
  <pre><code>public class SimpleThreads {
  //Display a message, preceded by the name of the current thread
  static void threadMessage(String message) {
  long threadName = Thread.currentThread().getId();
  System.out.format("id is %d: %s%n", threadName, message);
  }
  private static class MessageLoop implements Runnable {
      String info[];
      MessageLoop(String x[]) {
          info = x;
      }
      public void run() {
          try {
              for (int i = 1; i &lt; info.length; i++) {
                  //Pause for 4 seconds
                  Thread.sleep(4000);
                  //Print a message
                  threadMessage(info[i]);
              }
          } catch (InterruptedException e) {
              threadMessage("I wasn't done!");
          }
      }
  }
  
  public static void main(String args[])throws InterruptedException {
      //Delay, in milliseconds before we interrupt MessageLoop
      //thread (default one minute).
      long extent = 1000 * 60;//one minute
      String[] nargs =  {"33","ONE", "TWO"};
      if (args.length != 0) nargs = args;
      else System.out.println("assumed: java SimpleThreads 33 ONE TWO");
      try {
          extent = Long.parseLong(nargs[0]) * 1000;
      } catch (NumberFormatException e) {
          System.err.println("First Argument must be an integer.");
          System.exit(1);
      }
      threadMessage("Starting MessageLoop thread");
      long startTime = System.currentTimeMillis();
      Thread t = new Thread(new MessageLoop(nargs));
      t.start();
  
      threadMessage("Waiting for MessageLoop thread to finish");
      //loop until MessageLoop thread exits
      int seconds = 0;
      while (t.isAlive()) {
          threadMessage("Seconds:  " + seconds++);
          //Wait maximum of 1 second for MessageLoop thread to
          //finish.
          t.join(1000);
          if (((System.currentTimeMillis() - startTime) &gt; extent) &amp;&amp;
                  t.isAlive()) {
              threadMessage("Tired of waiting!");
              t.interrupt();
              //Shouldn't be long now -- wait indefinitely
              t.join();
          }
  
      }
      threadMessage("All done!");
      }
  }
  </code></pre>