Java併發之線程組ThreadGroup介紹

線程組介紹

線程組(ThreadGroup)簡單來講就是一個線程集合。線程組的出現是爲了更方便地管理線程。github

線程組是父子結構的,一個線程組能夠集成其餘線程組,同時也能夠擁有其餘子線程組。從結構上看,線程組是一個樹形結構,每一個線程都隸屬於一個線程組,線程組又有父線程組,這樣追溯下去,能夠追溯到一個根線程組——System線程組。編程

<div align=center>多線程


</div>併發

下面介紹一下線程組樹的結構:函數

  1. JVM建立的system線程組是用來處理JVM的系統任務的線程組,例如對象的銷燬等。
  2. system線程組的直接子線程組是main線程組,這個線程組至少包含一個main線程,用於執行main方法。
  3. main線程組的子線程組就是應用程序建立的線程組。

你能夠在main方法中看到JVM建立的system線程組和main線程組:post

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輸出:this

systenThreadGroup name = system
mainThreadGroup name = main

一個線程能夠訪問其所屬線程組的信息,但不能訪問其所屬線程組的父線程組或者其餘線程組的信息。spa

線程組的構造

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

做者資源

做者:濤哥 ( ijiangtao.net ) 公衆號:西召 ( westcall ) 歡迎 評論、關注、打賞,轉發和點贊,你的鼓勵是我持續創做的動力。 濤哥這裏,乾貨和溼貨,包羅萬象!
相關文章
相關標籤/搜索