获取JVM中所有正在运行的线程

时间:2015-05-09 03:33:20

标签: java jvm java-threads

我愿意运行另一个jar文件并获取其线程,所以我认为以这种方式运行jar将在当前JVM上运行jar:

Process p = Runtime.getRuntime().exec("java -jar " + path);

然后得到这样的线程:

ThreadGroup rootThreadGroup = null;

ThreadGroup getRootThreadGroup( ) {
    if ( rootThreadGroup != null )
        return rootThreadGroup;
    ThreadGroup tg = Thread.currentThread( ).getThreadGroup( );
    ThreadGroup ptg;
    while ( (ptg = tg.getParent( )) != null )
        tg = ptg;
    return tg;
}

Thread[] getAllThreads( ) {
    final ThreadGroup root = getRootThreadGroup( );
    final ThreadMXBean thbean = ManagementFactory.getThreadMXBean( );
    int nAlloc = thbean.getThreadCount( );
    int n = 0;
    Thread[] threads;
    do {
        nAlloc *= 2;
        threads = new Thread[ nAlloc ];
        n = root.enumerate( threads, true );
    } while ( n == nAlloc );
    return java.util.Arrays.copyOf( threads, n );
}

但它没有显示我之前运行过的新jar线程,即使我将Thread.sleep(4000);行等待一点点。
是不是想让所有线程都在JVM中运行? code source

0 个答案:

没有答案