如何知道已创建并运行了多少个线程?

2022-09-01 20:26:37

这是我在Java中的简单程序:

public class Counter extends Thread {

    public static void main(String args[]) {    
        Thread t1 = new Thread();
        Thread t2 = new Thread();
        t1.start();
        t2.start();
    }
}

我使用的是 Windows 操作系统 32 位。我的问题是,我们如何知道程序中创建了多少个线程以及运行了多少个线程?有没有这样的工具?


答案 1

System.out.println(“来自给定线程的活动线程数:” + Thread.activeCount());


答案 2

Thread.getAllStackTraces()将为您提供一个映射,其中每个线程都是关键。然后,您可以检查每个线程的状态并检查 。thread.isAlive()

Map<Thread, StackTraceElement[]> threads = Thread.getAllStackTraces();