How To Display All Running Threads In Java ?
Last Updated :
18 Apr, 2022
A thread is basically a stream of instruction executed sequentially. It is used to implement multitasking in a program. A program can have multiple threads. Threads are used to do multiple things at the same time. Threads are basically used to perform complicated tasks in the background without affecting the main program.
There are two methods to display all running threads in Java
1. Using The ThreadGroup Object
Java provides us a way to group multiple threads in a single object. In Java, a group of threads ie thread groups is being implemented by ThreadGroup class, so here we will be using a ThreadGroup object to group all the threads currently running. After this, we will be using the activeCount() method of ThreadGroup to get the number of active threads, then we will use the enumerate(Thread[] list) method of the ThreadGroup which will copy the currently active threads in an array, and we will loop over the array to get the names of all the active threads.
Java
import java.io.*;
class GFGThread extends Thread {
public void run()
{
System.out.println( "Overridden Run Method" );
}
}
public class GFG {
public static void main(String[] args)
{
GFGThread t1 = new GFGThread();
GFGThread t2 = new GFGThread();
t1.start();
t2.start();
ThreadGroup threadGroup
= Thread.currentThread().getThreadGroup();
int threadCount = threadGroup.activeCount();
Thread threadList[] = new Thread[threadCount];
threadGroup.enumerate(threadList);
System.out.println( "Active threads are:" );
for ( int i = 0 ; i < threadCount; i++)
System.out.println(threadList[i].getName());
}
}
|
2. Using getAllStackTrace() Method
The getAllStackTrace() method gives a stack trace of all the running threads. Then we make a set of the keys of that element because the method returns a map, and then we loop over all the elements of the set to print all the running threads.
Java
import java.io.*;
import java.lang.*;
import java.util.*;
class GFGThread extends Thread {
public void run()
{
System.out.println( "Overridden Run Method" );
}
}
public class GFG {
public static void main(String[] args)
{
GFGThread t1 = new GFGThread();
GFGThread t2 = new GFGThread();
t1.start();
t2.start();
Set<Thread> threadSet
= Thread.getAllStackTraces().keySet();
for (Thread x : threadSet) {
System.out.println(x.getName());
}
}
}
|
Output
Overridden Run Method
Overridden Run Method
Thread-0
Reference Handler
Thread-1
Signal Dispatcher
main
Finalizer
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...