当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java ThreadGroup activeCount()用法及代码示例


ThreadGroup类activeCount()方法

  • activeCount() 方法可在java.lang包。
  • activeCount() 方法是一个静态方法,它也可以通过类名访问。
  • activeCount() 方法用于返回当前线程线程组中的活动线程数。
  • activeCount() 方法当没有活动线程处于活动状态时不会引发任何异常。

用法:

    static int activeCount();

参数:

  • 此方法不接受任何参数。

返回值:

这个方法的返回类型是int,它返回线程组当前线程中的活动线程数。

例:

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

import java.lang.*;

class ActiveCount 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) {
        ActiveCount ac = new ActiveCount();
        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, ac, "First Thread");
            Thread th2 = new Thread(tg2, ac, "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 thread in:" + tg1.getName() + "-");
            System.out.println(tg1.activeCount());

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


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

        } catch (Exception ex) {

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

输出

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


相关用法


注:本文由纯净天空筛选整理自Preeti Jain大神的英文原创作品 Java ThreadGroup class activeCount() method with example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。