java - 了解由特定线程启动的线程数

标签 java multithreading

在下面的程序中,main 线程调用 startThread,它在一个新线程上启动。它调用 greet_thread,后者又调用 在新线程上问候startThread 调用 greet_thread 直到 count 小于或等于 10

有什么方法可以知道当前有多少线程正在运行?更具体地说,我想知道当前通过调用 greet_thread 启动的线程数。由于greet_thread被调用了10次,显然10个线程最后会单独运行。但是有没有办法知道这个数字?

这是程序中启动的线程的层次结构:

main_thread
  | 
 \ /
starts a new thread by calling startThread
  |
 \ /
startThread starts a new thread by calling greet_thread-->--|
  |                                                         |
 \ /                                                       \ / gets called 10 times
 greetThread is started with an infinite loop------<------- |
  |
 \ /
 greet() method is called

class Tester {

    private static  int count = 0;

    public static void main(String args[]) {
        startThread();
    }

    public static void startThread() {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                while(count <= 10) {
                    greet_thread(count);
                    count++;
                }
            }
        };
        new Thread(r).start();
    }

    public static void greet_thread(final int count) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                while(true) {
                    greet();
                }
            }
        };
        new Thread(r).start();
    }

    public static void greet() {
        System.out.println("GREET !");
    }
}

最佳答案

如果您有 30K 个线程在运行,您就会遇到问题。我怀疑你没有这么多 CPU。您可以使用 VisualVM、线程组或线程池或使用计数器来检查线程数。

通常当你设计一个程序时,你知道你想要多少个线程,你只需要检查是否是这种情况。您不会故意编写一个线程数未知但非常多的程序,然后尝试找出它是什么,因为这个数字不会很有用。

关于java - 了解由特定线程启动的线程数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15880074/

相关文章:

当进程是守护进程时,python 的多处理模块的 join()

java - 在 Tomcat7 上部署 webapp

java - 获取带有 fragment 的布局的 inflate ViewGroup

C++线程应用程序运行速度比非线程慢

android - 有没有更好的方法可以在协程中设置n次监听器?

swift - iOS 13 : threading violation: expected the main thread

java - JAXB:在类上生成注释列表

java - 如何列出 Java 中对象扩展的所有类?

java - 如何制作序列号表格? "-"在中间分开

java - 带双重检查锁的延迟加载与类级初始化的黑白比较