在以下程序中,main
线程调用在新线程上startThread
开始。它调用greet_thread
又greet
在新线程上调用。startThread
调用greet_thread
直到count is less than or equal to 10
.
有什么办法可以告诉我当前正在运行多少个线程?更具体地说,我想知道当前通过调用启动的线程数greet_thread
。正如greet_thread
所谓10 times
的,很明显10 threads
最后会单独运行。但是有没有办法知道这个数字?
这是程序中启动的线程的层次结构:
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 !");
}
}