Code snippet to get list of threads started by main thread:
import java.util.Set; public class ThreadSet { public static void main(String args[]) throws Exception{ Thread.currentThread().setName("ThreadSet"); for ( int i=0; i< 3; i++){ Thread t = new Thread(new MyThread()); t.setName("MyThread:"+i); t.start(); } Set<Thread> threadSet = Thread.getAllStackTraces().keySet(); for ( Thread t : threadSet){ if ( t.getThreadGroup() == Thread.currentThread().getThreadGroup()){ System.out.println("Thread :"+t+":"+"state:"+t.getState()); } } } } class MyThread implements Runnable{ public void run(){ try{ Thread.sleep(5000); }catch(Exception err){ err.printStackTrace(); } } }
output:
Thread :Thread[MyThread:2,5,main]:state:TIMED_WAITING Thread :Thread[MyThread:0,5,main]:state:TIMED_WAITING Thread :Thread[MyThread:1,5,main]:state:TIMED_WAITING Thread :Thread[ThreadSet,5,main]:state:RUNNABLE
If you need all threads including system threads, which have not been started by your program, remove below condition.
if ( t.getThreadGroup() == Thread.currentThread().getThreadGroup())
Now output:
Thread :Thread[MyThread:2,5,main]:state:TIMED_WAITING Thread :Thread[Reference Handler,10,system]:state:WAITING Thread :Thread[MyThread:1,5,main]:state:TIMED_WAITING Thread :Thread[ThreadSet,5,main]:state:RUNNABLE Thread :Thread[MyThread:0,5,main]:state:TIMED_WAITING Thread :Thread[Finalizer,8,system]:state:WAITING Thread :Thread[Signal Dispatcher,9,system]:state:RUNNABLE Thread :Thread[Attach Listener,5,system]:state:RUNNABLE