ThreadGroup(线程组)定义
线程组可以看做是存放线程的容器,ThreadGroup与Thread可以看做是集合与元素的对应关系,在ThreadGroup可以对组内的线程进行操作,比如destory() ,interrupt() ,以及设置线程组的最大优先级,从而限制新建线程的优先级。
ThreadGroup源码如下:
成员变量
public class ThreadGroup implements Thread.UncaughtExceptionHandler {
/* 父线程组*/
private final ThreadGroup parent;
/* 名字 */
String name;
/* 最大优先级*/
int maxPriority;
/* 是否销毁*/
boolean destroyed;
/* 是否守护*/
boolean daemon;
boolean vmAllowSuspension;
/* 未开始线程数量*/
int nUnstartedThreads = 0;
/* 存活线程数量*/
int nthreads;
/* 线程数组*/
Thread threads[];
/* 子线程组数*/
int ngroups;
/* 子线程组数组*/
ThreadGroup groups[];
构造方法
/* 私有无参构造,创建一个空线程组,为系统线程组,最大优先级就是线程的最大优先级(10),没有父线程组*/
private ThreadGroup() { // called from C code
this.name = "system";
this.maxPriority = Thread.MAX_PRIORITY;
this.parent = null;
}
/* 对外构造方法,传入线程组名字,实质上是获取执行创建线程的线程组为父线程组*/
public ThreadGroup(String name) {
this(Thread.currentThread().getThreadGroup(), name);
}
/* 对外构造方法,传入线程组名字,线程组对象,将校验线程是否具有修改权限*/
public ThreadGroup(ThreadGroup parent, String name) {
this(checkParentAccess(parent), parent, name);
}
/* 线程组私有构造,传入父线程组,以及名字*/
private ThreadGroup(Void unused, ThreadGroup parent, String name) {
this.name = name; //名字赋值
this.maxPriority = parent.maxPriority; //最大优先级赋值
this.daemon = parent.daemon; //是否守护
this.vmAllowSuspension = parent.vmAllowSuspension;
this.parent = parent; //父线程组赋值
parent.add(this); //将当前线程组添加到父线程组
}
核心方法
/* 检查父线程组的权限*/
private static Void checkParentAccess(ThreadGroup parent) {
parent.checkAccess();
return null;
}
/* 获取线程组的名字*/
public final String getName() {
return name;
}
/* 获取父线程组*/
public final ThreadGroup getParent() {
if (parent != null)
parent.checkAccess();
return parent;
}
/* 获取线程组中的最大优先级*/
public final int getMaxPriority() {
return maxPriority;
}
/* 是否守护*/
public final boolean isDaemon() {
return daemon;
}
/* 是否销毁,加锁执行*/
public synchronized boolean isDestroyed() {
return destroyed;
}
/* 设置守护*/
public final void setDaemon(boolean daemon) {
//检查当前线程是否具有修改权限
checkAccess();
this.daemon = daemon;
}
/* 设置线程组最大优先级,包括子线程组的最高优先级*/
public final void setMaxPriority(int pri) {
int ngroupsSnapshot;
ThreadGroup[] groupsSnapshot;
synchronized (this) {
//验证当前线程是都具有修改权限
checkAccess();
//传入优先级不合法
if (pri < Thread.MIN_PRIORITY || pri > Thread.MAX_PRIORITY) {
return;
}
//如果存在父线程组,当前线程组的最大优先级不能大于父线程组的最大优先级
maxPriority = (parent != null) ? Math.min(pri, parent.maxPriority) : pri;
//子线程数赋值
ngroupsSnapshot = ngroups;
if (groups != null) {
//含有子线程,复制到临时数组中
groupsSnapshot = Arrays.copyOf(groups, ngroupsSnapshot);
} else {
groupsSnapshot = null;
}
}
// 递归设置子线程组的最高优先级
for (int i = 0 ; i < ngroupsSnapshot ; i++) {
groupsSnapshot[i].setMaxPriority(pri);
}
}
/* 判断传入线程组是否为当前线程组的祖先线程组(或是否是当前线程组)*/
public final boolean parentOf(ThreadGroup g) {
//向上查找父线程组,直到查找父线程组为空,判断g是否为当前线程组的祖先线程组(或者是否为当前线程)
for (; g != null ; g = g.parent) {
//第一次判断传入线程组是否是当前线程组
if (g == this) {
return true;
}
}
return false;
}
/* 判断线程是否具有修改权限*/
public final void checkAccess() {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkAccess(this);
}
}
/* 返回线程组中活动线程的估计数,包含子线程组中的存活数量*/
public int activeCount() {
int result;
int ngroupsSnapshot;
ThreadGroup[] groupsSnapshot;
synchronized (this) {
if (destroyed) {
//已经销毁
return 0;
}
//线程中存活线程数
result = nthreads;
//子线程数
ngroupsSnapshot = ngroups;
if (groups != null) {
groupsSnapshot = Arrays.copyOf(groups, ngroupsSnapshot);
} else {
groupsSnapshot = null;
}
}
//循环子线程组,累加存活线程数
for (int i = 0 ; i < ngroupsSnapshot ; i++) {
result += groupsSnapshot[i].activeCount();
}
return result;
}
/* 将所有存活线程复制到指定数组中*/
public int enumerate(Thread list[]) {
//验证当前线程是否具有修改权限
checkAccess();
return enumerate(list, 0, true);
}
/**
* 将所有存活线程复制到指定数组中
* rescurse 否还包括作为此线程组的子组的线程组中的线程。
*/
public int enumerate(Thread list[], boolean recurse) {
//验证当前线程是否具有修改权限
checkAccess();
return enumerate(list, 0, recurse);
}
/* 私有调用方法, rescurse 否还包括作为此线程组的子组的线程组中的线程, n 是list中已经存在的元素(线程)数量*/
private int enumerate(Thread list[], int n, boolean recurse) {
int ngroupsSnapshot = 0;
ThreadGroup[] groupsSnapshot = null;
synchronized (this) {
if (destroyed) {
//线程组已经销毁
return 0;
}
// 线程组中的存活线程数量赋值
int nt = nthreads;
// nt不能大于list的可用长度(递归遍历子孙线程组的时候,会带上n,所以此处要减去n)
if (nt > list.length - n) {
nt = list.length - n;
}
for (int i = 0; i < nt; i++) {
if (threads[i].isAlive()) {
//线程存活,添加进数组
list[n++] = threads[i];
}
}
if (recurse) {
//包含子线程组
ngroupsSnapshot = ngroups;
if (groups != null) {
groupsSnapshot = Arrays.copyOf(groups, ngroupsSnapshot);
} else {
groupsSnapshot = null;
}
}
}
if (recurse) {
//包含子线程组,添加
for (int i = 0 ; i < ngroupsSnapshot ; i++) {
n = groupsSnapshot[i].enumerate(list, n, true);
}
}
return n;
}
/* 返回线程组及其子线程组的线程数量*/
public int activeGroupCount() {
int ngroupsSnapshot;
ThreadGroup[] groupsSnapshot;
synchronized (this) {
if (destroyed) {
// 线程组已经销毁
return 0;
}
// 子线程数赋值
ngroupsSnapshot = ngroups;
if (groups != null) {
//子线程组数组不为空
groupsSnapshot = Arrays.copyOf(groups, ngroupsSnapshot);
} else {
groupsSnapshot = null;
}
}
int n = ngroupsSnapshot;
for (int i = 0 ; i < ngroupsSnapshot ; i++) {
n += groupsSnapshot[i].activeGroupCount();
}
return n;
}
/* 将此线程组中每个存活的子线程组复制到该线程组中*/
public int enumerate(ThreadGroup list[]) {
checkAccess();
return enumerate(list, 0, true);
}
/**
* 将此线程组中每个存活的子线程组复制到该线程组中,
* 如果recurse=true,该子线程组的子线程组中的存活线程组也会被复制到这个线程组中,
*/
public int enumerate(ThreadGroup list[], boolean recurse) {
checkAccess();
return enumerate(list, 0, recurse);
}
/**
* 将此线程组中每个存活的子线程组复制到该线程组中,
* 如果recurse=true,该子线程组的子线程组中的存活线程组也会被复制到这个线程组中,
*/
private int enumerate(ThreadGroup list[], int n, boolean recurse) {
int ngroupsSnapshot = 0;
ThreadGroup[] groupsSnapshot = null;
synchronized (this) {
if (destroyed) {
return 0;
}
int ng = ngroups;
if (ng > list.length - n) {
ng = list.length - n;
}
if (ng > 0) {
System.arraycopy(groups, 0, list, n, ng);
n += ng;
}
if (recurse) {
ngroupsSnapshot = ngroups;
if (groups != null) {
groupsSnapshot = Arrays.copyOf(groups, ngroupsSnapshot);
} else {
groupsSnapshot = null;
}
}
}
if (recurse) {
for (int i = 0 ; i < ngroupsSnapshot ; i++) {
n = groupsSnapshot[i].enumerate(list, n, true);
}
}
return n;
}
/* 过期方法 */
@Deprecated
public final void stop() {
if (stopOrSuspend(false))
Thread.currentThread().stop();
}
/* 停止线程组中的所有线程*/
public final void interrupt() {
int ngroupsSnapshot;
ThreadGroup[] groupsSnapshot;
synchronized (this) {
checkAccess();
for (int i = 0 ; i < nthreads ; i++) {
threads[i].interrupt();
}
ngroupsSnapshot = ngroups;
if (groups != null) {
groupsSnapshot = Arrays.copyOf(groups, ngroupsSnapshot);
} else {
groupsSnapshot = null;
}
}
//同样作用于子线程组中的线程
for (int i = 0 ; i < ngroupsSnapshot ; i++) {
groupsSnapshot[i].interrupt();
}
}
/* 过期方法 */
@Deprecated
@SuppressWarnings("deprecation")
public final void suspend() {
if (stopOrSuspend(true))
Thread.currentThread().suspend();
}
/* 线程组中线程停止或者中断*/
@SuppressWarnings("deprecation")
private boolean stopOrSuspend(boolean suspend) {
boolean suicide = false;
Thread us = Thread.currentThread();
int ngroupsSnapshot;
ThreadGroup[] groupsSnapshot = null;
synchronized (this) {
checkAccess();
for (int i = 0 ; i < nthreads ; i++) {
if (threads[i]==us)
suicide = true;
else if (suspend)
threads[i].suspend();
else
threads[i].stop();
}
ngroupsSnapshot = ngroups;
if (groups != null) {
groupsSnapshot = Arrays.copyOf(groups, ngroupsSnapshot);
}
}
for (int i = 0 ; i < ngroupsSnapshot ; i++)
suicide = groupsSnapshot[i].stopOrSuspend(suspend) || suicide;
return suicide;
}
/* 过期方法 */
@Deprecated
@SuppressWarnings("deprecation")
public final void resume() {
int ngroupsSnapshot;
ThreadGroup[] groupsSnapshot;
synchronized (this) {
checkAccess();
for (int i = 0 ; i < nthreads ; i++) {
threads[i].resume();
}
ngroupsSnapshot = ngroups;
if (groups != null) {
groupsSnapshot = Arrays.copyOf(groups, ngroupsSnapshot);
} else {
groupsSnapshot = null;
}
}
for (int i = 0 ; i < ngroupsSnapshot ; i++) {
groupsSnapshot[i].resume();
}
}
/*销毁这个线程组及其子线程组,这个线程组必须为空,说明这个线程组中的所有的线程都已经停止了 */
public final void destroy() {
int ngroupsSnapshot;
ThreadGroup[] groupsSnapshot;
synchronized (this) {
checkAccess();
if (destroyed || (nthreads > 0)) {
throw new IllegalThreadStateException();
}
ngroupsSnapshot = ngroups;
if (groups != null) {
groupsSnapshot = Arrays.copyOf(groups, ngroupsSnapshot);
} else {
groupsSnapshot = null;
}
if (parent != null) {
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);
}
}
/*向当前线程组添加子线程组*/
private final void add(ThreadGroup g){
synchronized (this) {
if (destroyed) {
throw new IllegalThreadStateException();
}
if (groups == null) {
groups = new ThreadGroup[4];//初始长度为3
} else if (ngroups == groups.length) {
groups = Arrays.copyOf(groups, ngroups * 2);//成倍扩容
}
groups[ngroups] = g;
// This is done last so it doesn't matter in case the
// thread is killed
//子线程组数量加1
ngroups++;
}
}
/* 删除子线程组*/
private void remove(ThreadGroup g) {
synchronized (this) {
if (destroyed) {
return;
}
//删除
for (int i = 0 ; i < ngroups ; i++) {
if (groups[i] == g) {
ngroups -= 1;
System.arraycopy(groups, i + 1, groups, i, ngroups - i);
// Zap dangling reference to the dead group so that
// the garbage collector will collect it.
groups[ngroups] = null;
break;
}
}
if (nthreads == 0) {
notifyAll();
}
if (daemon && (nthreads == 0) &&
(nUnstartedThreads == 0) && (ngroups == 0))
{
destroy();
}
}
}
/* 将未开始线程数加1 */
void addUnstarted() {
synchronized(this) {
if (destroyed) {
throw new IllegalThreadStateException();
}
nUnstartedThreads++;
}
}
/*添加线程*/
void add(Thread t) {
synchronized (this) {
if (destroyed) {
throw new IllegalThreadStateException();
}
if (threads == null) {
threads = new Thread[4]; //初始容量为4
} else if (nthreads == threads.length) {
threads = Arrays.copyOf(threads, nthreads * 2); //成倍扩容
}
//复制
threads[nthreads] = t;
//存活线程数加1
nthreads++;
//未开始线程数减1
nUnstartedThreads--;
}
}
/*线程启动失败,删除线程,未成功启动线程数加1*/
void threadStartFailed(Thread t) {
synchronized(this) {
remove(t);
nUnstartedThreads++;
}
}
/**
线程执行完毕后调用,在线程组中删除该线程,
*/
void threadTerminated(Thread t) {
synchronized (this) {
remove(t);
if (nthreads == 0) {
notifyAll();
}
if (daemon && (nthreads == 0) &&
(nUnstartedThreads == 0) && (ngroups == 0))
{
destroy();
}
}
}
/* 删除线程 */
private void remove(Thread t) {
synchronized (this) {
if (destroyed) {
return;
}
for (int i = 0 ; i < nthreads ; i++) {
if (threads[i] == t) {
System.arraycopy(threads, i + 1, threads, i, --nthreads - i);
// Zap dangling reference to the dead thread so that
// the garbage collector will collect it.
threads[nthreads] = null;
break;
}
}
}
}
/* 输出线程*/
public void list() {
list(System.out, 0);
}
/* 输出线程*/
void list(PrintStream out, int indent) {
int ngroupsSnapshot;
ThreadGroup[] groupsSnapshot;
synchronized (this) {
for (int j = 0 ; j < indent ; j++) {
out.print(" ");
}
out.println(this);
indent += 4;
for (int i = 0 ; i < nthreads ; i++) {
for (int j = 0 ; j < indent ; j++) {
out.print(" ");
}
out.println(threads[i]);
}
ngroupsSnapshot = ngroups;
if (groups != null) {
groupsSnapshot = Arrays.copyOf(groups, ngroupsSnapshot);
} else {
groupsSnapshot = null;
}
}
for (int i = 0 ; i < ngroupsSnapshot ; i++) {
groupsSnapshot[i].list(out, indent);
}
}
/**
* 当此线程组中的线程因为一个未捕获的异常而停止,并且线程没有安装特定 Thread.UncaughtExceptionHandler 时,
* 由 Java Virtual Machine 调用此方法。
*/
public void uncaughtException(Thread t, Throwable e) {
if (parent != null) {
parent.uncaughtException(t, e);
} else {
Thread.UncaughtExceptionHandler ueh =
Thread.getDefaultUncaughtExceptionHandler();
if (ueh != null) {
ueh.uncaughtException(t, e);
} else if (!(e instanceof ThreadDeath)) {
System.err.print("Exception in thread \""
+ t.getName() + "\" ");
e.printStackTrace(System.err);
}
}
}
/*过期方法*/
@Deprecated
public boolean allowThreadSuspension(boolean b) {
this.vmAllowSuspension = b;
if (!b) {
VM.unsuspendSomeThreads();
}
return true;
}
/* toString*/
public String toString() {
return getClass().getName() + "[name=" + getName() + ",maxpri=" + maxPriority + "]";
}
}