在下面的程序中,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/