线程组( ThreadGroup)
JDK1.8 介绍
A thread group represents a set of threads. In addition, a thread group can also include other thread groups. The thread groups form a tree in which every thread group except the initial thread group has a parent.
A thread is allowed to access information about its own thread group, but not to access information about its thread group’s parent thread group or any other thread groups.
-
线程组是一个树形的结构,线程组有自己的父线程组,线程又可以作为树的叶子节点`
-
API描述上,说只允许访问自己线程组的信息,不允许访问父类或者兄弟的,但是经过实验发现:
线程组之间只读的方法是依然可以访问的
,如getName,activeCount,enumerate
有两个构造方法:
- 指定创建此线程组的线程组为父线程组:
ThreadGroup(String name)
- 指定创建特定的线程组为父线程组:
ThreadGroup(ThreadGroup parent, String name)
常用API
API作用 | 方法名称 | 说明 |
---|---|---|
评估当前活跃的线程数 | activeCount() | |
评估当前活跃的子线程组数 | activeGroupCount() | |
判断当前线程是否有权限更改线程组的状态 | checkAccess() | |
销毁此线程组 | destroy() | 此线程组如果还有活跃的线程或者已经被销毁,会抛出异常 |
拷贝线程组的线程到一个数组中 | enumerate(Thread[] list) | |
拷贝时赋予一个true,代表递归本线程组和子线程组,如果为false,则只拿本线程组的 | enumerate(Thread[] list, boolean recurse) | |
会打断线程组内全部的线程 | interrupt() | 包括子线程组的线程都会中断 |
设置线程组内全部的线程为守护线程 | setDaemon(boolean daemon) | 跟Thread方法不同,设置完成后,线程组在其最后一个线程死亡后,会自动销毁该线程组,主要做自动回收处理 |
API代码测试
public class ThreadGroupAPI {
public static void main(String[] args) throws InterruptedException {
ThreadGroup tg1 = new ThreadGroup("TG1");
Thread t1 = new Thread(tg1, "t1") {
@Override
public void run() {
// while (true) {
try {
Thread.sleep(1_000);
} catch (InterruptedException e) {
e.printStackTrace();
// break;
}
// }
}
};
// tg1.setDaemon(true);
t1.start();
Thread.sleep(2_000);
System.out.println(tg1.isDestroyed());
tg1.destroy();
System.out.println(tg1.isDestroyed());
//
// ThreadGroup tg2 = new ThreadGroup(tg1, "TG2");
// Thread t2 = new Thread(tg2, "T2") {
// @Override
// public void run() {
// while (true) {
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// break;
// }
// }
// }
// };
//
// t2.start();
//
// System.out.println(tg1.activeCount());
// System.out.println(tg1.activeGroupCount());
// t2.checkAccess();
tg1.destroy();
//
// System.out.println("=========================");
// Thread[] ts1 = new Thread[tg1.activeCount()];
// tg1.enumerate(ts1);
// Arrays.asList(ts1).forEach(System.out::println);
//
// System.out.println("=========================");
// tg1.enumerate(ts1, true);
// Arrays.asList(ts1).forEach(System.out::println);
//
// System.out.println("=========================");
// ts1 = new Thread[10];
// Thread.currentThread().getThreadGroup().enumerate(ts1, false);
// Arrays.asList(ts1).forEach(System.out::println);
// tg1.interrupt();
}
}