Java ThreadGroup类activeCount()方法及示例
ThreadGroup类activeCount()方法
activeCount()方法在java.lang包中可用。
activeCount()方法是静态方法,也可以使用类名进行访问。
activeCount()方法用于返回当前线程线程组中活动线程的数量。
当没有活动线程处于活动状态时,activeCount()方法不会引发任何异常。
语法:
static int activeCount();
参数:
此方法不接受任何参数。
返回值:
此方法的返回类型为int,它返回线程组中当前线程中活动线程的计数。
示例
//Java程序演示的例子
//activeCount()ThreadGroup类的方法。
import java.lang.*;
class ActiveCount extends Thread {
//覆盖run()Thread类
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 {
//我们正在创建ThreadGroup类的对象
ThreadGroup tg1 = new ThreadGroup("ThreadGroup 1");
ThreadGroup tg2 = new ThreadGroup("ThreadGroup 2");
//我们正在创建Thread类的对象,然后
//我们正在分配两个线程的ThreadGroup-
Thread th1 = new Thread(tg1, ac, "First Thread");
Thread th2 = new Thread(tg2, ac, "Second Thread");
//start()使用Thread类对象的调用方法
//线程类
th1.start();
th2.start();
//中计数活动线程
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
热门推荐
10 祖国生日祝福语简短英文
11 生日祝福语 简短独特高考
12 特别的端午祝福语简短
13 青春告白祖国简短祝福语
14 2026年春节祝福语简短
15 简短的出行工作祝福语
16 启程出发路途祝福语简短
17 登上舞台祝福语大全简短
18 职场祝福语大全 简短精辟