序文
ThreadGroupは、その名前が示すように、スレッドのグループです。ただし、これはオブジェクトであるため、一連のスレッドを持つ管理者として理解できます。ThreadGroupの管理者は、建物の寮と同様に、いくつかの管理方法を提供します。寮の管理者が必要です。これの利点は、特定の機能を管理するのに便利なことです。たとえば、エピデミックが発生した今、誰もが糸になっています。エピデミック防止担当者が一人ずつ体温を測定すると、間違いなく圧倒されるので、寮の事務局に「これの温度測定はあなたの責任です。建物。" したがって、ThreadGroupはそのような統合された管理ロールです。
分析は変数から始まります
变量成员如下:
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[]; // 存储子线程组的数组集合
その可変構造から、スレッドグループ全体が次のツリーで構成されていることがわかります。
では、ルートノード
のThreadGroupは誰ですか?ThreadGroupのコンストラクターは次のように語っています。
通过该构造器创建根节点:
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);
}
何ができるか
小切手
boolean parentOf(ThreadGroup g) // 是不是它父亲
boolean isDaemon() //是不是守护线程组
int getMaxPriority() // 最大优先级
synchronized boolean isDestroyed() // 线程组是否已消亡
int activeCount() // 活着的线程还有多少
int activeGroupCount() // 活着的子线程组有多少
バッチの中断、一時停止など。
void interrupt()
このグループのすべてのスレッドに割り込むだけでなく、すべての子スレッドグループのスレッドにも割り込む
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();
}
}
消える
このスレッドグループを終了すると、その下のすべての子スレッドグループが停止します。そして、このグループを親スレッドグループから削除します。
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);
}
}
総括する
ThreadGroupは、スレッドのバッチ管理のためのいくつかのメソッドを提供します。これはある程度の利便性をもたらしますが、不適切な使用はさまざまな異常を引き起こす可能性があります。