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);
}
}