/Users/lyon/j4p/src/thread/RaceThread.java
|
1 package thread;
2
3 public class RaceThread extends Thread {
4
5 public void run() {
6 while (true) {
7 printThreadGroups();
8 try {
9 Thread.sleep(10000);
10 } catch (InterruptedException e) {
11 }
12
13 }
14 }
15
16
17 public ThreadGroup getSystemThreadGroup() {
18
19 ThreadGroup systemThreadGroup;
20 ThreadGroup parentThreadGroup;
21
22 systemThreadGroup = Thread.currentThread().getThreadGroup();
23
24 while ((parentThreadGroup = systemThreadGroup.getParent()) != null)
25 systemThreadGroup = parentThreadGroup;
26
27 return systemThreadGroup;
28 }
29
30
31 public ThreadGroup[] getThreadGroupsArray() {
32
33 ThreadGroup systemThreadGroup = getSystemThreadGroup();
34
35 int numberOfGroups = systemThreadGroup.activeGroupCount() + 1;
36
37 ThreadGroup threadGroupsArray[] = new
38 ThreadGroup[numberOfGroups];
39
40 systemThreadGroup.enumerate(threadGroupsArray);
41
42 threadGroupsArray[numberOfGroups] = systemThreadGroup;
43
44 return threadGroupsArray;
45 }
46
47 public Thread[] getThreadsArray() {
48
49 ThreadGroup systemThreadGroup = getSystemThreadGroup();
50
51 Thread threadsArray[] = new Thread[systemThreadGroup.activeCount()];
52 systemThreadGroup.enumerate(threadsArray);
53
54 return threadsArray;
55 }
56
57 public void printThreadGroups() {
58 getSystemThreadGroup().list();
59 }
60
61 public void printThreads() {
62 Thread[] threadsArray = getThreadsArray();
63 for (int i = 0; i < threadsArray.length; i++)
64 System.out.println(threadsArray[i]);
65 }
66
67 public void printThreadsAndGroups() {
68 System.out.println("The threads are:");
69 printThreads();
70 System.out.println("The groups are:");
71 printThreadGroups();
72 }
73
74 }