activeCount()
包java.lang.Thread.activeCount()中提供了此方法。
此方法是静态的,因此也可以使用类名访问此方法,例如Thread.activeCount()。
此方法用于返回当前线程线程组中活动线程的数量。
此方法的返回类型为int,因此它返回整数类型值,并且活动线程将以数字计数。
当没有活动线程处于活动状态时,此方法不会引发异常。
语法:
static int activeCount(){
}
参数:
我们不会在File方法中将任何对象作为参数传递。
返回值:
此方法的返回类型为int,它以数字计数活动线程。
activeCount()
方法示例/* We will use Thread class methods so we are importing
the package but it is not mandate because it is
imported by default
*/
import java.lang.Thread;
public class MainThread {
public static void main(String[] args) {
//通过使用currentThread()Thread类将返回
//当前正在执行的线程的引用。
Thread th = Thread.currentThread();
//通过使用setName()方法,我们设置名称
//当前执行线程的数量
th.setName("Main Thread");
//通过使用setPriority()方法,我们将优先级设置为
//当前执行线程
th.setPriority(2);
//显示当前执行线程
System.out.println("Currently Executing Thread is :" + th);
int active_thread = Thread.activeCount();
//显示当前线程线程组中活动线程的数量
System.out.println("The Number of active threads is : " + active_thread);
Thread[] thread = new Thread[active_thread];
//active_thread保留在数组中
Thread.enumerate(thread);
//如果我们有多个线程,则循环打印活动线程。
for (int i = 0; i < active_thread; ++i)
System.out.println("Display active threads is " + thread[i]);
}
}
输出结果
E:\Programs>javac MainThread.java
E:\Programs>java MainThread
Currently Executing Thread is :Thread[Main Thread,2,main]
The Number of active threads is : 1
Display active threads is Thread[Main Thread,2,main]