當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java ThreadGroup activeGroupCount()用法及代碼示例


ThreadGroup類activeGroupCount()方法

  • activeGroupCount() 方法可在java.lang包。
  • activeGroupCount() 方法用於返回此線程組及其子組中的所有活動線程組。估計返回的結果,以便它返回該線程組中活動線程組的數量,並且可能會在運行時發生變化。
  • activeGroupCount() 方法是一個靜態方法,因此它也可以通過類名訪問。
  • activeGroupCount() 方法不是最終方法,因此它是可覆蓋的(即,如果我們願意,此方法在子類中是可覆蓋的)。

用法:

    public static int activeGroupCount();

參數:

  • 此方法不接受任何參數。

返回值:

這個方法的返回類型是int,它返回該線程組中的所有活動線程組。

例:

// Java program to demonstrate the example of 
// activeGroupCount() method of ThreadGroup Class.

import java.lang.*;

class ActiveGroupCount extends Thread {
    // Override run() of Thread class
    public void run() {
        String name = Thread.currentThread().getName();
        System.out.println(name + " " + "finish executing");
    }
}

public class Main {
    public static void main(String[] args) {
        ActiveGroupCount gac = new ActiveGroupCount();

        try {

            // We are creating an object of ThreadGroup class
            ThreadGroup tg1 = new ThreadGroup("ThreadGroup 1");
            ThreadGroup tg2 = new ThreadGroup("ThreadGroup 2");

            // We are creating an object of Thread class, and
            // we are assigning the ThreadGroup of both the thread

            Thread th1 = new Thread(tg1, gac, "First Thread");
            Thread th2 = new Thread(tg2, gac, "Second Thread");

            // Calling start() method with Thread class object 
            // of Thread class

            th1.start();
            th2.start();

            // Here we are counting active thread in ThreadGroup

            System.out.print("Active Group in:" + tg1.getName() + "-");
            System.out.println(tg1.activeGroupCount());

            System.out.print("Active Group in:" + tg2.getName() + "-");
            System.out.println(tg2.activeGroupCount());


            th1.join();
            th2.join();

        } catch (Exception ex) {

            System.out.println(ex.getMessage());
        }
    }
}

輸出

E:\Programs>javac Main.java
E:\Programs>java Main
First Thread finish executing
Second Thread finish executing
Active Group in:ThreadGroup 1-0
Active Group in:ThreadGroup 2-0


相關用法


注:本文由純淨天空篩選整理自Preeti Jain大神的英文原創作品 Java ThreadGroup class activeGroupCount() method with example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。