深入浅出Java多线程(十)之ThreadGroup详解(下)

335 阅读2分钟

这是我参与8月更文挑战的第20天,活动详情查看:8月更文挑战

ThreadGroup的基本操作

  • activeCount() 用于获取group中活跃的线程,这只是估计值,并不能百分之百地保证数字一定正确,原因前面已经分析过了,该方法会递归获取其他子group中的活跃线程。
  • activeGroupCount() 用于获取group中活跃的子group,这也是一个近似估值,该方法也会递归获取所有的子group数量。
  • getMaxPriority() 获取group的优先级,默认情况下,group的优先级为10,线程的优先级不能比group高
  • getName() 获取group名称
  • getParent() 获取当前group的父级group,无则返回null
  • list() 等价于System.out 输出活跃线程信息
  • parentOf( ThreadGroup g) 判断传参group 是否为当前调用的父级group
  • setMaxPriority( int pri) 指定group的优先级 重点:修改group优先级,导致原有的线程比它大(不会报错);新加入的线程才遵守

ThreadGroup 的 interrupt

thread group 调用 interrupt方法,会导致当前group内的所有avtice线程都被interrupt

  • 源码:
    public final void interrupt() {
        int ngroupsSnapshot;
        ThreadGroup[] groupsSnapshot;
        synchronized (this) {
            checkAccess();
            for (int i = 0 ; i < nthreads ; i++) {
                //重点 ↓ 循环每个线程 并调用 interrupt
                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();
        }
    }

ThreadGroup的destroy

destory() 方法用于销毁线程组,该方法只针对当前group内没有任何active 线程执行,调用后父group将本身删除;
销毁 ThreadGroup 及其子 ThreadGroup , 在该ThreadGroup中所有的线程必须是空,也就是说 ThreadGroup 或者 子ThreadGroup所有的线程都已经停止运行,如果有Active线程存在,调用destroy方法会抛出异常。

Destroys this thread group and all of its subgroups. This thread group must be empty,indicating that all threads that had been in this thread group have since stopped.
    public static void main(String[] args) throws InterruptedException {
        ThreadGroup threadGroup= new ThreadGroup("as");
        ThreadGroup main = Thread.currentThread().getThreadGroup();
        System.out.println("This thread destroy = "+ threadGroup.isDestroyed());
        main.list();
        threadGroup.destroy();
        System.out.println("This thread destroy = "+ threadGroup.isDestroyed());
        main.list();
        
    }

守护 ThreadGroup

  • 线程可以设置为守护线程,守护线程是一种特殊的线程,就像它的名字一样,它是系统的守护者。在后台默默的完成一些系统性的服务,比如垃圾回收线程、JIT线程就可以理解为守护线程。与之相应的是用户线程,用户线程可以认为是系统的工作线程,它会完成这个程序应该要完成的业务操作。如果用户线程全部结束,则意味着这个程序实际上无事可做了。守护线程要守护的对象已经不存在了,那么整个应用程序就应该结束。因此一个Java应用内只有守护线程时,Java虚拟机就会自然退出。
  • ThreadGroup也可以设置成守护 ThreadGroup,如果将group设置为daemon,并不会影响线程的daemon属性;如果一个group的daemon 设置成true,那么在group中没有任何active线程时, 该group将会自动destroy。

本章总结

在本章中,详细介绍了 ThreadGroup 与 Thread 的关系 , ThreadGroup 并不是用来管理 Thread 的,而是针对Thread的一个组织;ThreadGroup提供了较多的API,本章中几乎对所有的API都进行了介绍