一、什么是线程组
线程组ThreadGroup表示一组线程的集合。可以把线程归属到某一个线程组中,线程组中可以有线程对象,也可以有线程组,这样的组织结构有点类似于树的形式。
通常情况下根线程组是system线程组。system线程组下是main线程组,默认情况下第一级应用自己的线程组是通过main线程组创建出来的。
二、线程组的作用
ThreadGroup是为了方便线程管理出现了,可以统一设定线程组的一些属性,比如setDaemon,设置未处理异常的处理方法,设置统一的安全策略等等;也可以通过线程组方便的获得线程的一些信息。
三、线程组的使用
通过现场组可以将未处理异常已经被统一处理:
package cn.outofmemory.concurrent;import java.net.SocketException;public class ThreadGroupDemo2 {public static void main(String[] args) {ThreadGroup spiderGroup = new SpiderThreadGroup("spiderGroup");//可以统一设定线程是否为守护线程spiderGroup.setDaemon(true);//可以设置线程组内的最大优先级spiderGroup.setMaxPriority(Thread.NORM_PRIORITY);//初始化线程Thread spiderThread = new Thread(spiderGroup, new Runnable() {@Overridepublic void run() {throw new RuntimeException(new SocketException());}});//启动线程spiderThread.start();}/*** 此类从ThreadGroup类继承重写了其uncaughtException方法,对于SocketException进行了特殊处理* @author outofmemory.cn**/static class SpiderThreadGroup extends ThreadGroup {public SpiderThreadGroup(String name) {super(name);}public void uncaughtException(Thread t, Throwable e) {if (e.getCause() instanceof SocketException) {System.out.println("socket exception should be process");} else {super.uncaughtException(t, e);}}}}// 运行结果:socket exception should be process
通过线程组,方便的获得应用中一共有多少个活动线程,并打印这些活动线程的名字:
package cn.outofmemory.concurrent;public class ThreadDemo3 {public static void main(String[] args) {ThreadGroup g = Thread.currentThread().getThreadGroup();while (g != null) {ThreadGroup temp = g.getParent();if (temp == null) {break;}g = temp;}//现在g就是根线程组System.out.println("active count is " + g.activeCount());Thread[] all = new Thread[g.activeCount()];g.enumerate(all);for (Thread t : all) {System.out.println(t.getName());}}}/*输出结果:(main是代码run所在的线程,其他都是虚拟机启动的线程)active count is 5Reference HandlerFinalizerSignal DispatcherAttach Listenermain*/
四、线程组与线程池的区别
参考资料: java线程组(ThreadGroup)

