Get a list of all threads currently running in Java

后端 未结 13 1483
[愿得一人]
[愿得一人] 2020-11-22 02:30

Is there any way I can get a list of all running threads in the current JVM (including the threads not started by my class)?

Is it also possible to get the

13条回答
  •  再見小時候
    2020-11-22 03:20

    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 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
    

提交回复
热议问题