What is the Thread.enumerate() function in Java?

The static Thread.enumerate() function duplicates every thread group and subgroup into a specified array. This method takes a Thread type array tarray as a parameter and calls the enumerate function.

enumerate uses the activeCount() method to assess the length of the array. The extra threads (out of bound) will be ignored if the length of the defined array is too short.

Syntax


static int enumerate(Thread[] tarray)

Parameters

  • tarray: an array of Thread class objects where the thread’s group and subgroup are to be copied.

Return value

This function returns the number of threads put into the specified array.

Example

// Load java class
import java.lang.Thread;
public class Main {
public static void main(String[] args) {
Thread th1 = Thread.currentThread();
th1.setName("Main Thread");
// printing the recent thread
System.out.println("All Recent Threads = " + th1);
int count = Thread.activeCount();
System.out.println("recently active threads = " + count);
Thread tarray[] = new Thread[count];
/* returning the number of threads
that are copied into the specified array
*/
Thread.enumerate(tarray);
// printing active threads
int i = 0;
while(i != count){
System.out.println(i + ": " + tarray[i]);
i++;
}
}
}

Free Resources