/**
* Destroys this thread group and all of its subgroups. This thread
* group must be empty, indicating that all threads that had been in
* this thread group have since stopped.
* <p>
* First, the <code>checkAccess</code> method ofthis thread group is
* called withno arguments; this may result in a security exception.
*
* @exception IllegalThreadStateException if the thread group isnot
* empty orif the thread group has already been destroyed.
* @exception SecurityException if the current thread cannot modify this
* thread group.
* @see java.lang.ThreadGroup#checkAccess()
* @since JDK1.0
*/
public final void destroy() {
int ngroupsSnapshot;
ThreadGroup[] groupsSnapshot;
synchronized (this) {
checkAccess();
if (destroyed || (nthreads > 0)) {
thrownew IllegalThreadStateException();
}
ngroupsSnapshot = ngroups;
if (groups != null) {
groupsSnapshot = Arrays.copyOf(groups, ngroupsSnapshot);
} else {
groupsSnapshot = null;
}
if (parent != null) {//除了name为system的ThreadGroup外,其他ThreadGroup都是有parent的
destroyed = true;
ngroups = 0;
groups = null;
nthreads = 0;
threads = null;
}
}
for (int i = 0 ; i < ngroupsSnapshot ; i += 1) {
groupsSnapshot[i].destroy();
}
if (parent != null) {
parent.remove(this);
}
}
/**
* Adds the specified thread to this thread group.
*
* <p> Note: This method is called from both library code
* and the Virtual Machine. It is called from VM to add
* certain system threads to the system thread group.
*
* @param t
* the Thread to be added
*
* @throws IllegalThreadStateException
* if the Thread group has been destroyed
*/void add(Thread t) {
synchronized (this) {
if (destroyed) {
thrownew IllegalThreadStateException();
}
if (threads == null) {
threads = new Thread[4];
} elseif (nthreads == threads.length) {
threads = Arrays.copyOf(threads, nthreads * 2);
}
threads[nthreads] = t;
// This is done last so it doesn't matter in case the// thread is killed
nthreads++;
// The thread is now a fully fledged member of the group, even// though it may, or may not, have been started yet. It will prevent// the group from being destroyed so the unstarted Threads count is// decremented.
nUnstartedThreads--;//因为Thread的start()方法执行后,会执行group.add(this),即未开始的线程数要-1。Thread的init(ThreadGroup g, Runnable target, String name,long stackSize, AccessControlContext acc)方法会执行g.addUnstarted(),即未开始执行的线程数+1
}
}