线程组介绍
线程组(ThreadGroup
)简单来说就是一个线程集合。线程组的出现是为了更方便地管理线程。
线程组是父子结构的,一个线程组可以集成其他线程组,同时也可以拥有其他子线程组。从结构上看,线程组是一个树形结构,每个线程都隶属于一个线程组,线程组又有父线程组,这样追溯下去,可以追溯到一个根线程组——System线程组。
image-20221117204248873
1.1 线程组的常用方法
获取当前的线程组名字
1
| Thread.currentThread().getThreadGroup().getName()
REASONML
|
复制线程组
1 2 3 4
| Thread[] threads = new Thread[threadGroup.activeCount()]; TheadGroup threadGroup = new ThreadGroup(); threadGroup.enumerate(threads);
JAVA
|
线程组统一异常处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| package com.func.axc.threadgroup;
public class ThreadGroupDemo { public static void main(String[] args) { ThreadGroup threadGroup1 = new ThreadGroup("group1") { public void uncaughtException(Thread t, Throwable e) { System.out.println(t.getName() + ": " + e.getMessage()); } };
Thread thread1 = new Thread(threadGroup1, new Runnable() { public void run() { throw new RuntimeException("测试异常"); } }); thread1.start(); }
}
JAVA
|
1.2 线程组的数据结构
线程组还可以包含其他的线程组,不仅仅是线程。
首先看看 ThreadGroup
源码中的成员变量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| 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[];
}
JAVA
|
然后看看构造函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| private ThreadGroup() { 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); }
JAVA
|
第三个构造函数里调用了checkParentAccess
方法,这里看看这个方法的源码:
1 2 3 4 5 6 7 8 9 10 11 12 13
| private static Void checkParentAccess(ThreadGroup parent) { parent.checkAccess(); return null; }
public final void checkAccess() { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkAccess(this); } }
JAVA
|
线程组是一个树状的结构,每个线程组下面可以有多个线程或者线程组。线程组可以起到统一控制线程的优先级和检查线程的权限的作用。