Java并发之线程组ThreadGroup介绍

本文涉及的产品
文本翻译,文本翻译 100万字符
图片翻译,图片翻译 100张
语种识别,语种识别 100万字符
简介: Java并发之线程组ThreadGroup介绍

线程组介绍

线程组(ThreadGroup)简单来说就是一个线程集合。线程组的出现是为了更方便地管理线程。

线程组是父子结构的,一个线程组可以集成其他线程组,同时也可以拥有其他子线程组。从结构上看,线程组是一个树形结构,每个线程都隶属于一个线程组,线程组又有父线程组,这样追溯下去,可以追溯到一个根线程组——System线程组。

![thread-group-tree](https://ucc.alicdn.com/images/user-upload-01/img_convert/c0e9ce5567a521ed2a07260181a70822.gif)

下面介绍一下线程组树的结构:

  1. JVM创建的system线程组是用来处理JVM的系统任务的线程组,例如对象的销毁等。
  2. system线程组的直接子线程组是main线程组,这个线程组至少包含一个main线程,用于执行main方法。
  3. main线程组的子线程组就是应用程序创建的线程组。

你可以在main方法中看到JVM创建的system线程组和main线程组:

public static void main(String[] args) {
      ThreadGroup mainThreadGroup=Thread.currentThread().getThreadGroup();
      ThreadGroup systenThreadGroup=mainThreadGroup.getParent();
      System.out.println("systenThreadGroup name = "+systenThreadGroup.getName());
      System.out.println("mainThreadGroup name = "+mainThreadGroup.getName());
  }

console输出:

systenThreadGroup name = system
mainThreadGroup name = main

一个线程可以访问其所属线程组的信息,但不能访问其所属线程组的父线程组或者其他线程组的信息。

线程组的构造

java.lang.ThreadGroup提供了两个构造函数:

Constructor Description
ThreadGroup(String name) 根据线程组名称创建线程组,其父线程组为main线程组
ThreadGroup(ThreadGroup parent, String name) 根据线程组名称创建线程组,其父线程组为指定的parent线程组

下面演示一下这两个构造函数的用法:

public static void main(String[] args) {
    ThreadGroup subThreadGroup1 = new ThreadGroup("subThreadGroup1");
    ThreadGroup subThreadGroup2 = new ThreadGroup(subThreadGroup1, "subThreadGroup2");
    System.out.println("subThreadGroup1 parent name = " + subThreadGroup1.getParent().getName());
    System.out.println("subThreadGroup2 parent name = " + subThreadGroup2.getParent().getName());
}

console输出:

subThreadGroup1 parent name = main
subThreadGroup2 parent name = subThreadGroup1

ThreadGroup方法介绍

ThreadGroup提供了很多有用的方法,下面提供了这些方法的简要介绍,以及部分方法的使用示例。

S.N. Method Description
1) void checkAccess() This method determines if the currently running thread has permission to modify the thread group.
2) int activeCount() This method returns an estimate of the number of active threads in the thread group and its subgroups.
3) int activeGroupCount() This method returns an estimate of the number of active groups in the thread group and its subgroups.
4) void destroy() This method destroys the thread group and all of its subgroups.
5) int enumerate(Thread[] list) This method copies into the specified array every active thread in the thread group and its subgroups.
6) int getMaxPriority() This method returns the maximum priority of the thread group.
7) String getName() This method returns the name of the thread group.
8) ThreadGroup getParent() This method returns the parent of the thread group.
9) void interrupt() This method interrupts all threads in the thread group.
10) boolean isDaemon() This method tests if the thread group is a daemon thread group.
11) void setDaemon(boolean daemon) This method changes the daemon status of the thread group.
12) boolean isDestroyed() This method tests if this thread group has been destroyed.
13) void list() This method prints information about the thread group to the standard output.
14) boolean parentOf(ThreadGroup g) This method tests if the thread group is either the thread group argument or one of its ancestor thread groups.
15) void suspend() This method is used to suspend all threads in the thread group.
16) void resume() This method is used to resume all threads in the thread group which was suspended using suspend() method.
17) void setMaxPriority(int pri) This method sets the maximum priority of the group.
18) void stop() This method is used to stop all threads in the thread group.
19) String toString() This method returns a string representation of the Thread group.

查看线程组信息

下面演示了查看当前线程组的信息。

public static void list(){
        ThreadGroup tg = new ThreadGroup ("subgroup 1");
        Thread t1 = new Thread (tg, "thread 1");
        Thread t2 = new Thread (tg, "thread 2");
        Thread t3 = new Thread (tg, "thread 3");
        tg = new ThreadGroup ("subgroup 2");
        Thread t4 = new Thread (tg, "my thread");
        tg = Thread.currentThread ().getThreadGroup ();
        int agc = tg.activeGroupCount ();
        System.out.println ("Active thread groups in " + tg.getName () + " thread group: " + agc);
        tg.list ();
}

输出如下:

Active thread groups in main thread group: 2
java.lang.ThreadGroup[name=main,maxpri=10]
    Thread[main,5,main]
    java.lang.ThreadGroup[name=subgroup 1,maxpri=10]
    java.lang.ThreadGroup[name=subgroup 2,maxpri=10]

终止线程组中的所有线程

一个线程应由其他线程来强制中断或停止,而是应该由线程自己自行停止。

因此 Thread.currentThread().stop(), Thread.currentThread().suspend(), Thread.currentThread().resume() 都已经被废弃了。

interrupt() 方法的作用是通知线程应该中断了,具体到底中断还是继续运行,由被通知的线程处理。

public class ThreadGroupExampleInterrupt {

    public static void main(String[] args) {

        // Start two threads
        MyThread mt = new MyThread();
        mt.setName("A");
        mt.start();
        mt = new MyThread();
        mt.setName("B");
        mt.start();

        // Wait 2 seconds
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // Interrupt all methods in the same thread group as the main thread
        Thread.currentThread().getThreadGroup().interrupt();

    }


    //一个启动以后进入等待,直到被interrupt的线程
    static class MyThread extends Thread {
        public void run() {
            synchronized ("A") {
                System.out.println(getName() + " about to wait.");
                try {
                    "A".wait();
                } catch (InterruptedException e) {
                    System.out.println(getName() + " interrupted.");
                }
                System.out.println(getName() + " terminating.");
            }
        }
    }

}

执行main方法输出:

A about to wait.
B about to wait.
A interrupted.
A terminating.
B interrupted.
B terminating.

总结

本节介绍了线程组(ThreadGroup)的概念,及其结构和构造函数,并演示了使用线程组方便地管理组内线程的几个方法。

本节是并发系列教程的一节,更多相关教程可以访问文章后面的链接。

后续会有更多关于并发编程的知识点的介绍,并且会结合企业项目进行实战介绍,欢迎继续关注。

Links

作者资源

相关资源

目录
相关文章
|
3天前
|
存储 缓存 安全
深度剖析Java HashMap:源码分析、线程安全与最佳实践
深度剖析Java HashMap:源码分析、线程安全与最佳实践
|
4天前
|
缓存 前端开发 JavaScript
一篇文章助你搞懂java中的线程概念!纯干货,快收藏!
【8月更文挑战第11天】一篇文章助你搞懂java中的线程概念!纯干货,快收藏!
13 0
一篇文章助你搞懂java中的线程概念!纯干货,快收藏!
|
3天前
|
算法 安全 Java
深入解析Java多线程:源码级别的分析与实践
深入解析Java多线程:源码级别的分析与实践
|
4天前
|
Java 程序员 调度
深入浅出Java多线程编程
Java作为一门成熟的编程语言,在多线程编程方面提供了丰富的支持。本文将通过浅显易懂的语言和实例,带领读者了解Java多线程的基本概念、创建方法以及常见同步工具的使用,旨在帮助初学者快速入门并掌握Java多线程编程的基础知识。
4 0
|
4天前
|
Java
java中获取当前执行线程的名称
这篇文章介绍了两种在Java中获取当前执行线程名称的方法:使用`Thread`类的`getName`方法直接获取本线程的名称,以及使用`Thread.currentThread()`方法获取当前执行对象的引用再调用`getName`方法。
|
4天前
|
Java 测试技术
Java SpringBoot Test 单元测试中包括多线程时,没跑完就结束了
Java SpringBoot Test 单元测试中包括多线程时,没跑完就结束了
10 0
|
5天前
|
Java
Java多线程-死锁的出现和解决
死锁是指多线程程序中,两个或以上的线程在运行时因争夺资源而造成的一种僵局。每个线程都在等待其中一个线程释放资源,但由于所有线程都被阻塞,故无法继续执行,导致程序停滞。例如,两个线程各持有一把钥匙(资源),却都需要对方的钥匙才能继续,结果双方都无法前进。这种情况常因不当使用`synchronized`关键字引起,该关键字用于同步线程对特定对象的访问,确保同一时刻只有一个线程可执行特定代码块。要避免死锁,需确保不同时满足互斥、不剥夺、请求保持及循环等待四个条件。
|
Java API
Java线程组ThreadGroup
Java线程组ThreadGroup
102 0
Java线程组ThreadGroup
|
7天前
|
安全 Java 数据处理
Java并发编程:解锁多线程的潜力
在数字化时代的浪潮中,Java作为一门广泛使用的编程语言,其并发编程能力是提升应用性能和响应速度的关键。本文将带你深入理解Java并发编程的核心概念,探索如何通过多线程技术有效利用计算资源,并实现高效的数据处理。我们将从基础出发,逐步揭开高效并发编程的面纱,让你的程序运行得更快、更稳、更强。
|
6天前
|
Java 开发者
奇迹时刻!探索 Java 多线程的奇幻之旅:Thread 类和 Runnable 接口的惊人对决
【8月更文挑战第13天】Java的多线程特性能显著提升程序性能与响应性。本文通过示例代码详细解析了两种核心实现方式:Thread类与Runnable接口。Thread类适用于简单场景,直接定义线程行为;Runnable接口则更适合复杂的项目结构,尤其在需要继承其他类时,能保持代码的清晰与模块化。理解两者差异有助于开发者在实际应用中做出合理选择,构建高效稳定的多线程程序。
27 7