All ITKnowledge Source Code Search Tips Advanced Search |

| Mastering Java Threads by Marc Adler and David Herst DDC Publishing, Inc. ISBN: 1562438425 Pub Date: 05/01/99

Search this book:

Previous | Table of Contents | Next

### An Example of Programming with ThreadGroups

The following is an example of an Applet that continually lists all of the threads that are operating in the Java VM. It shows how to obtain the root ThreadGroup of the system and how to (recursively) enumerate all of the ThreadGroups that are descendants of the root ThreadGroup.

LISTTHREADS.JAVA

    import java.applet.*;
    import java.awt.*;

    class ListThreads extends Applet implements Runnable
    {
      LTFrame m_frame;
      Thread m_thread;
      boolean m_bShutdown = false;
      long m_ulSleepInterval = 5000;

      public void init() {
      {
        m_frame = new LTFrame(”ThreadLister”, this);
        m_frame.show();
        m_thread = new Thread(this);
        m_thread.start();
      }

      public void stop ()
      {
      }

      public void destroy()
      {
        super.stop();
      }

      public void terminate()
      {
       m_bShutdown = true;
       if (m_thread != null)
       {
        m_thread.stop();
        m_thread = null;
       }
      }

      public void run()
      {
        while (!m-bShutdown)
        {

          m_frame.getListbox().clear();
          showThreadGroupsRecursively(getRootThreadGroup(), 0);
          try
          {
             Thread.sleep(m_ulSleepInterval);
          }
          catch (InterruptedException ie)
          {
             return;
          }
            catch (NullPointerException ne)
          {
             return;
           catch (Exception e)

          {
             return;
           }
         }
      }

      public Thread getThread()
      {
        return m_thread;
      }

      protected synchronized void
       showThreadGroupsRecursively(ThreadGroup tg, int level)
      {
      if (tg == null)
        return;

      String strItem = new String();

      for (int i = 0; i <level; i++)
      strItem += “ ”;
      strltem += tg.toString();
      m_frame.getListbox().addItem(strItem);

      int nGroups = tg.activeGroupCount ();
      if (nGroups == 0)
        return;

      ThreadGroup aThreadGroups[] = new ThreadGroup[nGroups];
      tg.enumerate(aThreadGroups, false);
        for (int i = 0; i < nGroups; i++)
        {
        showThreadGroupsRecursively(aThreadGroups[i], level+1);
        }
      }

      protected void showThreadGroups()
      {
        List 1stGroups = m_frame.getListbox();
        1stGroups.clear();

        ThreadGroup aThreadGroups[] = getListOfThreadGroups();
        if (aThreadGroups == null)
      {
         1stGroups.addItem(”There are no ThreadGroups here”);
         return;
      }

      for (int i = 0; i < aThreadGroups.length; i++)
      {
        ThreadGroup tg = aThreadGroups[i];
        1stGroups.addItem(tg.toStringo());
       }
      }

      protected ThreadGroup[] getListOfThreadGroups()
      {
        ThreadGroup tgRoot = getRootThreadGroupo();
       if (tgRoot == null)
           return null;
      int nGroups = tgRoot.activeGroupCounto () + 1;
      if (nGroups == 1)
        return null;

      ThreadGroup aThreadGroups[] = new ThreadGroup[nGroups];
      tgRoot.enumerate(aThreadGroups, true);

      for (int i = nGroups-1; i > 0; i--)
      {
      aThreadGroups[i] = aThreadGroups[i-1];
      }
      aThreadGroups[0] = tgRoot;

      return aThreadGroups;
      }

      public ThreadGroup getRootThreadGroup()
      {
       ThreadGroup tg = Thread.currentThread().getThreadGroup();
       ThreadGroup tgParent = tg;

       do
       {
       tg = tgParent;
        tgParent = tgParent.getParent();
      n } while (tgParent != null);

      return tg;
      }

     }
    class LTFrame extends Frame
    {
      protected ListThreads m_app;
      protected List m_listThreads;
      protected Button m_btnQuit;
      protected Butt m_btnSuspendPolling;
      protected boolean m_bSuspended = false;

      public LTFrame(String szTitle, ListThreads app)
      {
       super(szTitle);
       m_app = app;

       GridBagLayout layout = new GridBagLayout();
       setLayout(layout);

       GridBagConstraints gbc = new GridBagConstraints();

      // Put a listbox in the top half of the frame
      m_listThreads = new List(10, false);

      // Set up the GridBagConstraints so that the listbox
      // resizes both vertically and horizontally. The listbox
      // is anchored at the top of the frame.
      gbc.gridx = 0;
      gbc.gridy = 0;
      gbc.gridheight = 2;
      gbc.gridwidth = GridBagConstraints.REMAINDER;
      gbc.fill = GridBagConstraints.BOTH;
      gbc.anchor = GridBagConstraints.NORTHWEST;
      gbc.weighty = 1.0;
      gbc.weightx = 1.0;

      layout.setConstraints(m_listThreads, gbc);
      add(m_listThreads);

      // Create a panel which will be placed on the bottom
      // part of the frame
      Panel panel = new Panel();

      // Set up the GridBagConstraints so that the button bar does
      // not resize vertically, but *does* resize horizontally.
      // The button bar is anchored at the bottom of the frame.
      gbc.gridx = 0;
      gbc.gridy = GridBagConstraints.RELATIVE;
      gbc.gridheight = 1;
      gbc.gridwidth = GridBagConstraints.REMAINDER;
      gbc.fill = GridBagConstraints.HORIZONTAL;
      gbc.anchor = GridBagConstraints.SOUTHWEST;
      gbc.weighty = 0.0;
      gbc.weightx = 1.0;

      layout.setConstraints(panel, gbc);
       panel.setBackground(Color.blue);
       add(panel);

      // Create a button and add it to the bottom panel
      FlowLayout flowLayout = new FlowLayout(FlowLayout.CENTER);
      panel.setLayout(flowLayout);

      m_btnQuit = new Button(“Quit”);
      panel.add(m_btnQuit);
      m_btnSuspendPolling = new Button(“Suspend Polling”);
      panel.add(m_btnSuspendPolling);

      pack(); // components get their preferred size
      }

      public List getListbox()
      {
        return m_listThreads;
      }

      public boolean action(Event evt, Object what)
      {
      if (evt.target == m_btnQuit)
      {
         hide();
         dispose();
         m_app.terminate();
         return true;
      }
      else if (evt.target == m_btnSuspendPolling)
      {
      if (m_bSuspended) // If already suspended, resume
      {
        m_app.getThreado().resume();
        m-btnSuspendPolling.setLabel(”Suspend Polling”);
      }
      else
      {
        m_app.getThread().suspend();
        m_btnSuspendPolling.setLabel(”Resume Polling”);
      }
      m_bSuspended = !m_bSuspended;
         return true;
      }

       return false;
      }
     }

Lab 3: Enumerating Threads

Perform the following steps:

  1. Take the above example and extend it so that each thread within each ThreadGroup is enumerated and listed in hierarchical fashion.
  2. Add two buttons that allow you to increase or decrease the priority of the highlighted thread.
  3. Ensure that you catch any SecurityException that might occur if you exceed the minimum or maximum bounds of the thread’s priority limit.

Previous | Table of Contents | Next

Copyright © DDC Publishing

Products | Contact Us | About Us | Privacy | Ad Info | Home Use of this site is subject to certain Terms & Conditions, Copyright © 1996-2000 EarthWeb Inc. All rights reserved. Reproduction in whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Read EarthWeb's privacy statement.