package threads;
public class TestThreadGroup extends Thread
{
public static void main(String[] args)
{
System.out.println(doWork());
}
static String doWork()
{
String s = dumpThreadGroupTree();
createThreadGroups();
s += dumpThreadGroupTree();
return s;
}
static String dumpThreadGroupTree()
{
ThreadGroup root = getRoot();
String s = "------Dump of ThreadGroup tree-----\n";
s += dump(root);
return s;
}
static void createThreadGroups()
{
ThreadGroup parentGroup =
new ThreadGroup("My New Parent ThreadGroup");
ThreadGroup childGroup =
new ThreadGroup(parentGroup,
"My New Child ThreadGroup");
Thread thread1 = new TestThreadGroup(parentGroup,
"My First Thread");
parentGroup.setMaxPriority(7);
Thread thread2 = new TestThreadGroup(parentGroup,
"My Second Thread");
Thread thread3 = new TestThreadGroup(childGroup,
"My Third Thread");
childGroup.setMaxPriority(5);
Thread thread4 = new TestThreadGroup(childGroup,
"My Fourth Thread");
}
TestThreadGroup(ThreadGroup tg, String name)
{
super(tg, name);
}
public void run()
{
for (int i = 0; i < 10000; i++)
{
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
// Ignore
}
}
}
static ThreadGroup getRoot()
{
ThreadGroup tg = Thread.currentThread().getThreadGroup();
while (true)
{
ThreadGroup parent = tg.getParent();
if (parent == null)
break;
tg = parent;
}
return tg;
}
static String dump(ThreadGroup tg)
{
String s = "";
String indent = "";
for (int i = 0; i < m_indent; i++)
indent += ONE_INDENT;
s += indent + "ThreadGroup \"" + tg.getName() + "\"\n";
s += indent + " Max priority : " + tg.getMaxPriority() + "\n";
s += indent + " Daemon : " + tg.isDaemon() + "\n";
// Dump the threads in this thread group
m_indent++;
// overestimate size
Thread[] threads = new Thread[tg.activeCount()];
tg.enumerate(threads);
for (int i = 0; i < threads.length; i++)
{
Thread t = threads[i];
if (t == null)
break;
if (t.getThreadGroup() == tg)
s += dump(t);
}
// Dump the thread groups in this thread group
ThreadGroup[] threadGroups =
new ThreadGroup[tg.activeGroupCount()];
// overestimate size
tg.enumerate(threadGroups);
for (int i = 0; i < threadGroups.length; i++)
{
ThreadGroup g = threadGroups[i];
if (g == null)
break;
if (g.getParent() == tg)
s += dump(g);
}
--m_indent;
return s;
}
static String dump(Thread t)
{
String s = "";
String indent = "";
for (int i = 0; i < m_indent; i++)
indent += ONE_INDENT;
s += indent + "Thread \"" + t.getName() + "\"\n";
s += indent + " Priority : " + t.getPriority() + "\n";
s += indent + " Daemon : " + t.isDaemon() + "\n";
return s;
}
//// Private data ////////
private static int m_indent = 0;
private static final String ONE_INDENT = " ";
} |