我试图写一个程序来测试java中父/子线程的执行效果!为什么活动线程数低于 3?其他线程会发生什么。这让我觉得 Java 可以拥有数百万个线程,但其中只有少数是活动的。这是正确的还是有别的?
public class ManyThreadsTester {
static int threadCount = 0;
static class recursiveRunnable implements Runnable{
@Override
public void run() {
System.out.println(threadCount);
// Arrives up to infinity if the System.exit(0) statement is absent!
try {
System.out.println("Active threads before: " + Thread.activeCount());
//Always prints 2
Thread.sleep(40);
threadCount++;
new Thread(new recursiveRunnable()).start();
} catch (InterruptedException ex) {
Logger.getLogger(ManyThreadsTester.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Active threads after: " + Thread.activeCount());
//Always prints 3
}
}
public static void main(String... args) throws InterruptedException{
Thread th = new Thread(new recursiveRunnable());
th.start();
Thread.sleep(5000);
System.out.print("FINAL ACTIVE THREAD COUNTS: " + Thread.activeCount());
//prints 2
System.exit(0);
}
}