Java Reference
In-Depth Information
simple Swing user interface and uses it to display a listing of its own threads. Fig-
ure 4-1 shows such a listing.
Figure 4−1. The threads and thread groups of a Swing application
The
listAllThreads()
method uses the static
Thread
method
currentThread()
to
obtain the current thread and then calls
getThreadGroup()
to find the thread
group of that thread. The method then uses the
ThreadGroup.getParent()
method
to move up through the thread-group hierarchy until it finds the root thread
group, the thread group that contains all other threads and thread groups.
Now
listAllThreads()
calls the private
ThreadLister.printGroupInfo()
method
to display the contents of the root thread group and then recursively display the
contents of all the thread groups it contains.
printGroupInfo()
, and the
print-
ThreadInfo()
method it calls, use various
Thread
and
ThreadGroup
methods to
obtain information about the threads and their groups. Note that the
isDaemon()
method returns whether a thread is a daemon thread or not. Daemon threads are
background threads that are not expected to exit. The Java interpreter exits when
all nondaemon threads have quit.
The
ThreadLister
class has a
main()
method, so it can be run as a standalone
program. It is more interesting, of course, to invoke the
listAllThreads()
method
from within another program; it can also help you to diagnose problems you are
having with threads.
Example 4−2: ThreadLister.java
package com.davidflanagan.examples.thread;
import java.io.*;
import java.awt.*; // AWT classes for the demo program
import javax.swing.*; // Swing GUI classes for the demo
/**
* This class contains a useful static method for listing all threads
* and threadgroups in the VM. It also has a simple main() method so it
* can be run as a standalone program.
**/
public class ThreadLister {
/** Display information about a thread. */