软件包java.lang.Thread.enumerate(Thread [] th)中提供了此方法。
此方法用于将当前线程线程组或其子组的所有活动线程复制到指定的数组中,该数组将作为方法中的参数给出。
此方法是静态的,因此也可以使用类名访问此方法,例如Thread.enumerate(Thread [] th)。
此方法的返回类型为int,它返回活动线程的数量,该数量将作为方法的参数保留在给定数组中。
如果访问权限拒绝该线程,则此方法会引发异常。
语法:
static int enumerate(Thread[] th){
}参数:
我们传递一个线程类型数组,该数组将保留当前线程线程组的所有活动线程。
返回值:
此方法的返回类型为int,它返回所有活动线程的计数,这些计数将作为方法的参数保留在数组中。
enumerate()方法示例/* 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 Enumerate {
public static void main(String[] args) {
//通过使用currentThread()Thread类将返回
//当前正在执行的线程的引用。
Thread th = Thread.currentThread();
//通过使用setName()方法,我们将名称设置为
//当前执行线程
th.setName("Enumerate Thread");
//通过使用setPriority()方法,我们设置
//当前执行线程的优先级
th.setPriority(2);
//显示当前执行线程
System.out.println("Currently Executing Thread is :" + th);
int active_thread = Thread.activeCount();
//显示当前线程线程组中活动线程的数量
System.out.println("The Current 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 Enumerate.java E:\Programs>java Enumerate Currently Executing Thread is :Thread[Enumerate Thread,2,main] The Current active threads is : 1 Display active threads is Thread[Enumerate Thread,2,main]