Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

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

Fouzia Bashir

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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++;
      }
   }
}

RELATED TAGS

java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring