Open In App

Java Thread.enumerate() Method

Last Updated : 24 Jan, 2025
Comments
Improve
Suggest changes
10 Likes
Like
Report

Thread.enumerate() method in Java is used to retrieve all active threads in the current thread's thread group, and it stores these threads in an array. This method provides a way to inspect the currently running threads in a program. It is a static method in the Thread class, which means it can be called on the Thread class itself rather than on a specific thread object.

Example 1: Below is an example that demonstrates the usage of Thread.enumerate().


Output
Active threads (limited by array size):
main
Thread-0
Thread-1

Explanation: In the above example, we create some thread objects and start them, which tries to enumerate all active threads using Thread.enumerate(), storing them in an array. Then it prints the names of the captured threads and highlights the limitations of Thread.enumerate() and the potential for missing threads if the provided array is too small.

Syntax of Thread.enumerate() Method

public static int enumerate(Thread[] threads) // Array of threads

  • Parameter: It takes a single parameter, threads, which is an array of Thread objects, and populates this array with the active threads.
  • Return type: It returns an integer, the number of threads that have been placed into the threads array.

Example 2: In this example, we perform specific tasks on each active thread, such as logging the thread's name or performing cleanup operations.


Output
Thread 2 is starting.
Thread 1 is starting.
Thread 2 has finished.
Thread 1 has finished.

Explanation: In the above example, we created two Geeks threads, started them, and then used Thread.enumerate() to get an array of currently active threads. It then iterates through the array, logging the name of each thread and checking if it is still alive. This example explains how to obtain information and perform actions on active threads.

Important points:

  • It is used for checking currently active threads in the JVM.
  • It prints the array of thread objects.
  • It helps in the inspection and analysis of running threads.

Next Article
Article Tags :
Practice Tags :

Similar Reads